Programs & Examples On #Carmen

Carmen is the name of a Ruby gem providing a repository of geographic regions and of a collection of software from Carnegie Mellon University for controlling mobile robots.

How to get current date time in milliseconds in android

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int mSec = calendar.get(Calendar.MILLISECOND);

How to get the entire document HTML as a string?

To also get things outside the <html>...</html>, most importantly the <!DOCTYPE ...> declaration, you could walk through document.childNodes, turning each into a string:

const html = [...document.childNodes]
    .map(node => nodeToString(node))
    .join('\n') // could use '' instead, but whitespace should not matter.

function nodeToString(node) {
    switch (node.nodeType) {
        case node.ELEMENT_NODE:
            return node.outerHTML
        case node.TEXT_NODE:
            // Text nodes should probably never be encountered, but handling them anyway.
            return node.textContent
        case node.COMMENT_NODE:
            return `<!--${node.textContent}-->`
        case node.DOCUMENT_TYPE_NODE:
            return doctypeToString(node)
        default:
            throw new TypeError(`Unexpected node type: ${node.nodeType}`)
    }
}

I published this code as document-outerhtml on npm.


edit Note the code above depends on a function doctypeToString; its implementation could be as follows (code below is published on npm as doctype-to-string):

function doctypeToString(doctype) {
    if (doctype === null) {
        return ''
    }
    // Checking with instanceof DocumentType might be neater, but how to get a
    // reference to DocumentType without assuming it to be available globally?
    // To play nice with custom DOM implementations, we resort to duck-typing.
    if (!doctype
        || doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
        || typeof doctype.name !== 'string'
        || typeof doctype.publicId !== 'string'
        || typeof doctype.systemId !== 'string'
    ) {
        throw new TypeError('Expected a DocumentType')
    }
    const doctypeString = `<!DOCTYPE ${doctype.name}`
        + (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
        + (doctype.systemId
            ? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
            : ``)
        + `>`
    return doctypeString
}

What is the best way to access redux store outside a react component?

For TypeScript 2.0 it would look like this:

MyStore.ts

export namespace Store {

    export type Login = { isLoggedIn: boolean }

    export type All = {
        login: Login
    }
}

import { reducers } from '../Reducers'
import * as Redux from 'redux'

const reduxStore: Redux.Store<Store.All> = Redux.createStore(reducers)

export default reduxStore;

MyClient.tsx

import reduxStore from "../Store";
{reduxStore.dispatch(...)}

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to get UTC time in Python?

Try this code that uses datetime.utcnow():

from datetime import datetime
datetime.utcnow()

For your purposes when you need to calculate an amount of time spent between two dates all that you need is to substract end and start dates. The results of such substraction is a timedelta object.

From the python docs:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

And this means that by default you can get any of the fields mentioned in it's definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10*6) / 10*6 computed with true division enabled.

How do I show running processes in Oracle DB?

This one shows SQL that is currently "ACTIVE":-

select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/

This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:

select
  object_name, 
  object_type, 
  session_id, 
  type,         -- Type or system/user lock
  lmode,        -- lock mode in which session holds lock
  request, 
  block, 
  ctime         -- Time since current mode was granted
from
  v$locked_object, all_objects, v$lock
where
  v$locked_object.object_id = all_objects.object_id AND
  v$lock.id1 = all_objects.object_id AND
  v$lock.sid = v$locked_object.session_id
order by
  session_id, ctime desc, object_name
/

This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.

COLUMN percent FORMAT 999.99 

SELECT sid, to_char(start_time,'hh24:mi:ss') stime, 
message,( sofar/totalwork)* 100 percent 
FROM v$session_longops
WHERE sofar/totalwork < 1
/

Find all files in a directory with extension .txt in Python

Many users have replied with os.walk answers, which includes all files but also all directories and subdirectories and their files.

import os


def files_in_dir(path, extension=''):
    """
       Generator: yields all of the files in <path> ending with
       <extension>

       \param   path       Absolute or relative path to inspect,
       \param   extension  [optional] Only yield files matching this,

       \yield              [filenames]
    """


    for _, dirs, files in os.walk(path):
        dirs[:] = []  # do not recurse directories.
        yield from [f for f in files if f.endswith(extension)]

# Example: print all the .py files in './python'
for filename in files_in_dir('./python', '*.py'):
    print("-", filename)

Or for a one off where you don't need a generator:

path, ext = "./python", ext = ".py"
for _, _, dirfiles in os.walk(path):
    matches = (f for f in dirfiles if f.endswith(ext))
    break

for filename in matches:
    print("-", filename)

If you are going to use matches for something else, you may want to make it a list rather than a generator expression:

    matches = [f for f in dirfiles if f.endswith(ext)]

Common elements comparison between 2 lists

The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:

l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]

The or True part is only necessary if you expect any elements to evaluate to False.

What does mscorlib stand for?

Microsoft Core Library, ie they are at the heart of everything.

There is a more "massaged" explanation you may prefer:

"When Microsoft first started working on the .NET Framework, MSCorLib.dll was an acronym for Microsoft Common Object Runtime Library. Once ECMA started to standardize the CLR and parts of the FCL, MSCorLib.dll officially became the acronym for Multilanguage Standard Common Object Runtime Library."

From http://weblogs.asp.net/mreynolds/archive/2004/01/31/65551.aspx

Around 1999, to my personal memory, .Net was known as "COOL", so I am a little suspicious of this derivation. I never heard it called "COR", which is a silly-sounding name to a native English speaker.

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

The type java.lang.CharSequence cannot be resolved in package declaration

"Java 8 support for Eclipse Kepler SR2", and the new "JavaSE-1.8" execution environment showed up automatically.

Download this one:- Eclipse kepler SR2

and then follow this link:- Eclipse_Java_8_Support_For_Kepler

WPF TabItem Header Styling

Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:

<Style TargetType="{x:Type TabItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type TabItem}">
        <Grid>
          <Border Name="Border" Margin="0,0,0,0" Background="Transparent"
                  BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
                              HorizontalAlignment="Center"
                              ContentSource="Header" Margin="12,2,12,2"
                              RecognizesAccessKey="True">
              <ContentPresenter.LayoutTransform>
            <RotateTransform Angle="270" />
          </ContentPresenter.LayoutTransform>
        </ContentPresenter>
          </Border>
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="True">
            <Setter Property="Panel.ZIndex" Value="100" />
            <Setter TargetName="Border" Property="Background" Value="Red" />
            <Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
          </Trigger>
          <Trigger Property="IsEnabled" Value="False">
            <Setter TargetName="Border" Property="Background" Value="DarkRed" />
            <Setter TargetName="Border" Property="BorderBrush" Value="Black" />
            <Setter Property="Foreground" Value="DarkGray" />
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

UTF-8: General? Bin? Unicode?

Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.

And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

Cursor adapter and sqlite example

CursorAdapter Example with Sqlite

...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...

class CustomAdapter extends CursorAdapter {
    // CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)

    public CustomAdapter(Context context, Cursor c) {
        super(context, c);
    }

    public void bindView(View view, Context context, Cursor cursor) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        // Get all the values
        // Use it however you need to
        TextView textView = (TextView) view;
        textView.setText(name);
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate your view here.
        TextView view = new TextView(context);
        return view;
    }
}

private final class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "db_name";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TIMELINE);
        db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
        db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public Cursor getAllContacts() {
        String selectQuery = "SELECT  * FROM table_name;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        return cursor;
    }
}

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

If you are not using https in api calls, Please add this key "App Uses Non-Exempt Encryption" in your info.plist and set it to "NO"

How to configure port for a Spring Boot application

Programmatically, with spring boot 2.1.5:

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory server) {
        server.setPort(9000);
    }

}

C++: Where to initialize variables in constructor

Option 1 allows you to initialize const members. This cannot be done with option 2 (as they are assigned to, not initialized).

Why must const members be intialized in the constructor initializer rather than in its body?

Undefined reference to vtable

Undefined reference to vtable may occur due to the following situation also. Just try this:

Class A Contains:

virtual void functionA(parameters)=0; 
virtual void functionB(parameters);

Class B Contains:

  1. The definition for the above functionA.
  2. The definition for the above functionB.

Class C Contains: Now you're writing a Class C in which you are going to derive it from Class A.

Now if you try to compile you will get Undefined reference to vtable for Class C as error.

Reason:

functionA is defined as pure virtual and its definition is provided in Class B. functionB is defined as virtual (NOT PURE VIRTUAL) so it tries to find its definition in Class A itself but you provided its definition in Class B.

Solution:

  1. Make function B as pure virtual (if you have requirement like that) virtual void functionB(parameters) =0; (This works it is Tested)
  2. Provide Definition for functionB in Class A itself keeping it as virtual . (Hope it works as I didn't try this)

Byte Array to Hex String

Using str.format:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1

or using format

>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1

Note: In the format statements, the 02 means it will pad with up to 2 leading 0s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101) would be formatted to "111" instead of "010101"

or using bytearray with binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'

Here is a benchmark of above methods in Python 3.6.1:

from timeit import timeit
import binascii

number = 10000

def using_str_format() -> str:
    return "".join("{:02x}".format(x) for x in test_obj)

def using_format() -> str:
    return "".join(format(x, "02x") for x in test_obj)

def using_hexlify() -> str:
    return binascii.hexlify(bytearray(test_obj)).decode('ascii')

def do_test():
    print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
    if using_str_format() != using_format() != using_hexlify():
        raise RuntimeError("Results are not the same")

    print("Using str.format       -> " + str(timeit(using_str_format, number=number)))
    print("Using format           -> " + str(timeit(using_format, number=number)))
    print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))

test_obj = bytes([i for i in range(255)])
do_test()

test_obj = bytearray([i for i in range(255)])
do_test()

Result:

Testing with 255-byte bytes:
Using str.format       -> 1.459474583090427
Using format           -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format       -> 1.443447684109402
Using format           -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684

Methods using format do provide additional formatting options, as example separating numbers with spaces " ".join, commas ", ".join, upper-case printing "{:02X}".format(x)/format(x, "02X"), etc., but at a cost of great performance impact.

Change HTML email body font type and size in VBA

Set texts with different sizes and styles, and size and style for texts from cells ( with Range)

Sub EmailManuellAbsenden()

Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String

Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
.GetInspector.Display
 ghOldBody = .htmlBody

 ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
 "<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
 Range("B5") & "<br>" & _
 Range("B6") & "<br>" & _
 "<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
 Range("B5")
 .htmlBody = ghNewBody & ghOldBody

 End With

End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts

How to display images from a folder using php - PHP

Here is a possible solution the solution #3 on my comments to blubill's answer:

yourscript.php
========================
<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if (file_exists($dir) == false) 
    {
        echo 'Directory "', $dir, '" not found!';
    } 
    else 
    {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) 
        {
            $file_type = strtolower(end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)     
            {
                $name = basename($file);
                echo "<img src='img.php?name={$name}' />";
            }
        }
    }
?>


img.php
========================
<?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/home/users/Pictures/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

Javascript Iframe innerHTML

document.getElementById('iframe01').outerHTML

Install tkinter for Python

Use ntk for your desktop application, which work on top of tkinter to give you more functional and good looking ui in less codding.

install ntk by pip install ntk

proper Documentation in here: ntk.readthedocs.io

Happy codding.

Is it possible to import a whole directory in sass using @import?

You could use a bit of workaround by placing a sass file in folder what you would like to import and import all files in that file like this:

file path:main/current/_current.scss

@import "placeholders"; @import "colors";

and in next dir level file you just use import for file what imported all files from that dir:

file path:main/main.scss

@import "EricMeyerResetCSSv20"; @import "clearfix"; @import "current";

That way you have same number of files, like you are importing the whole dir. Beware of order, file that comes last will override the matching stiles.

What does "Use of unassigned local variable" mean?

Not all code paths set a value for lateFee. You may want to set a default value for it at the top.

Eclipse DDMS error "Can't bind to local 8600 for debugger"

Worked for me, based on this answer

In Eclipse go to

Window->Preference->Android->DDMS

Then tick "Use ADBHOST" as "127.0.0.1".

Then just restart eclipse

Changing background color of selected item in recyclerview

Most Simpler Way From My Side is to Add a variable in adapterPage as last Clicked Position.

in onBindViewHolder paste this code which checks for last stored position matched with loading positions Constants is the class where i declare my global variables

if(Constants.LAST_SELECTED_POSITION_SINGLE_PRODUCT == position) {

    //change the view background here
    holder.colorVariantThumb.setBackgroundResource(R.drawable.selected_background);
}

//on view click you store the position value and notifyItemRangeChanged will 
// call the onBindViewHolder and will check the condition

holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view){
        Constants.LAST_SELECTED_POSITION_SINGLE_PRODUCT=position;
        notifyItemRangeChanged(0, mColorVariants.size());
    } 
});

ipynb import another ipynb file

There is no problem at all using Jupyter with existing or new Python .py modules. With Jupyter running, simply fire up Spyder (or any editor of your choice) to build / modify your module class definitions in a .py file, and then just import the modules as needed into Jupyter.

One thing that makes this really seamless is using the autoreload magic extension. You can see documentation for autoreload here:

http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html

Here is the code to automatically reload the module any time it has been modified:

# autoreload sets up auto reloading of modified .py modules
import autoreload
%load_ext autoreload
%autoreload 2

Note that I tried the code mentioned in a prior reply to simulate loading .ipynb files as modules, and got it to work, but it chokes when you make changes to the .ipynb file. It looks like you need to restart the Jupyter development environment in order to reload the .ipynb 'module', which was not acceptable to me since I am making lots of changes to my code.

Comment out HTML and PHP together

I found the following solution pretty effective if you need to comment a lot of nested HTML + PHP code.

Wrap all the content in this:

<?php
    if(false){
?>

Here goes your PHP + HTML code

<?php
    }
?>

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

To Enable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);

To Disable WiFi:

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);

Note: To access with WiFi state, we have to add following permissions inside the AndroidManifest.xml file:

android.permission.ACCESS_WIFI_STATE
android.permission.UPDATE_DEVICE_STATS 
android.permission.CHANGE_WIFI_STATE

What is a bus error?

My reason for bus error on Mac OS X was that I tried to allocate about 1Mb on the stack. This worked well in one thread, but when using openMP this drives to bus error, because Mac OS X has very limited stack size for non-main threads.

Setting width/height as percentage minus pixels

I use Jquery for this

function setSizes() {
   var containerHeight = $("#listContainer").height();
   $("#myList").height(containerHeight - 18);
}

then I bind the window resize to recalc it whenever the browser window is resized (if container's size changed with window resize)

$(window).resize(function() { setSizes(); });

Setting environment variables on OS X

My personal practice is .bash_profile. I'm adding paths there and append to Path variable,

GOPATH=/usr/local/go/bin/
MYSQLPATH=/usr/local/opt/[email protected]/bin

PATH=$PATH:$GOPATH:$MYSQLPATH

After then I can have individual Path by echo $GOPATH, echo$MYSQLPATH or all by echo $PATH.

How to improve performance of ngRepeat over a huge dataset (angular.js)?

The hottest - and arguably most scalable - approach to overcoming these challenges with large datasets is embodied by the approach of Ionic's collectionRepeat directive and of other implementations like it. A fancy term for this is 'occlusion culling', but you can sum it up as: don't just limit the count of rendered DOM elements to an arbitrary (but still high) paginated number like 50, 100, 500... instead, limit only to as many elements as the user can see.

If you do something like what's commonly known as "infinite scrolling", you're reducing the initial DOM count somewhat, but it bloats quickly after a couple refreshes, because all those new elements are just tacked on at the bottom. Scrolling comes to a crawl, because scrolling is all about element count. There's nothing infinite about it.

Whereas, the collectionRepeat approach is to use only as many elements as will fit in viewport, and then recycle them. As one element rotates out of view, it's detached from the render tree, refilled with data for a new item in the list, then reattached to the render tree at the other end of the list. This is the fastest way known to man to get new information in and out of the DOM, making use of a limited set of existing elements, rather than the traditional cycle of create/destroy... create/destroy. Using this approach, you can truly implement an infinite scroll.

Note that you don't have to use Ionic to use/hack/adapt collectionRepeat, or any other tool like it. That's why they call it open-source. :-) (That said, the Ionic team is doing some pretty ingenious things, worthy of your attention.)


There's at least one excellent example of doing something very similar in React. Only instead of recycling the elements with updated content, you're simply choosing not to render anything in the tree that's not in view. It's blazing fast on 5000 items, although their very simple POC implementation allows a bit of flicker...


Also... to echo some of the other posts, using track by is seriously helpful, even with smaller datasets. Consider it mandatory.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

Another way to solve this problem is to install the missing libs that you need.

You can download the libs and see how to install here.

File Upload to HTTP server in iphone programming

I used ASIHTTPRequest a lot like Jane Sales answer but it is not under development anymore and the author suggests using other libraries like AFNetworking.

Honestly, I think now is the time to start looking elsewhere.

AFNetworking works great, and let you work with blocks a lot (which is a great relief).

Here's an image upload example from their documentation page on github:

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

for more extendability for large scale apps use oop style with encapsulated fields.

Simple way :-

  class Fruit implements JsonSerializable {

        private $type = 'Apple', $lastEaten = null;

        public function __construct() {
            $this->lastEaten = new DateTime();
        }

        public function jsonSerialize() {
            return [
                'category' => $this->type,
                'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
            ];
        }
    }

echo json_encode(new Fruit()); //which outputs:

{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}

Real Gson on PHP :-

  1. http://jmsyst.com/libs/serializer
  2. http://symfony.com/doc/current/components/serializer.html
  3. http://framework.zend.com/manual/current/en/modules/zend.serializer.html
  4. http://fractal.thephpleague.com/ - serialize only

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Just got this error msg on my 32 bit Windows - I read the FAQ here: http://pythonware.com/products/pil/faq.htm and this sort of indicates that Windows is funny. Looked again at install pg and downloaded the Windows executable for Python26 # Python Imaging Library 1.1.7 for Python 2.6 (Windows only) - and the _imaging module gets installed when you run this. Should solve problem. So you can't just do the python setup.py install routine on: Python Imaging Library 1.1.7 Source Kit (all platforms) (November 15, 2009).

SQL-Server: The backup set holds a backup of a database other than the existing

In the Options, change the "Restore As" file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.

How would I run an async Task<T> method synchronously?

Or you could just go with:

customerList = Task.Run<List<Customer>>(() => { return GetCustomers(); }).Result;

For this to compile make sure you reference extension assembly:

System.Net.Http.Formatting

Boolean vs boolean in Java

Yes you can use Boolean/boolean instead.

First one is Object and second one is primitive type.

  • On first one, you will get more methods which will be useful.

  • Second one is cheap considering memory expense The second will save you a lot more memory, so go for it

Now choose your way.

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

How can I center <ul> <li> into div

use oldschool center-tags

<div> <center> <ul> <li>...</li> </ul></center> </div>

:-)

Can I install/update WordPress plugins without providing FTP access?

As stated before none of the perm fixes work anymore. You need to change the perms accordingly AND put the following in your wp-config.php:

define('FS_METHOD', 'direct');

C default arguments

Yes, with features of C99 you may do this. This works without defining new data structures or so and without the function having to decide at runtime how it was called, and without any computational overhead.

For a detailed explanation see my post at

http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/

Jens

Using pointer to char array, values in that array can be accessed?

When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:

printf("\nvalue:%c", (*ptr)[0]); , which is the same as *((*ptr)+0)

Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.

char arr[5] = {'a','b','c','d','e',0}; 
char *ptr = arr; //same as char *ptr = &arr[0]

printf("\nvalue:%c", ptr[0]);

How can I get the count of milliseconds since midnight for the current?

I tried a few ones above but they seem to reset @ 1000

This one definately works, and should also take year into consideration

long millisStart = Calendar.getInstance().getTimeInMillis();

and then do the same for end time if needed.

Quickest way to clear all sheet contents VBA

Try this one:

Sub clear_sht
  Dim sht As Worksheet
  Set sht = Worksheets(GENERATOR_SHT_NAME)
  col_cnt = sht.UsedRange.Columns.count
  If col_cnt = 0 Then
    col_cnt = 1
  End If

  sht.Range(sht.Cells(1, 1), sht.Cells(sht.UsedRange.Rows.count, col_cnt)).Clear
End Sub

How to embed YouTube videos in PHP?

This YouTube embed generator solve all my problems with video embedding.

How to generate a Makefile with source in sub-directories using just one makefile

This is another trick.

In main 'Makefile' define SRCDIR for each source dir and include 'makef.mk' for each value of SRCDIR. In each source dir put file 'files.mk' with list of source files and compile options for some of them. In main 'Makefile' one can define compile options and exclude files for each value of SRCDIR.

Makefile:

PRG             := prog-name

OPTIMIZE        := -O2 -fomit-frame-pointer

CFLAGS += -finline-functions-called-once
LDFLAGS += -Wl,--gc-section,--reduce-memory-overheads,--relax


.DEFAULT_GOAL   := hex

OBJDIR          := obj

MK_DIRS         := $(OBJDIR)


SRCDIR          := .
include         makef.mk

SRCDIR := crc
CFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE
ASFLAGS_crc := -DCRC8_BY_TABLE -DMODBUS_CRC_BY_TABLE
include makef.mk

################################################################

CC              := avr-gcc -mmcu=$(MCU_TARGET) -I.
OBJCOPY         := avr-objcopy
OBJDUMP         := avr-objdump

C_FLAGS         := $(CFLAGS) $(REGS) $(OPTIMIZE)
CPP_FLAGS       := $(CPPFLAGS) $(REGS) $(OPTIMIZE)
AS_FLAGS        := $(ASFLAGS)
LD_FLAGS        := $(LDFLAGS) -Wl,-Map,$(OBJDIR)/$(PRG).map


C_OBJS          := $(C_SRC:%.c=$(OBJDIR)/%.o)
CPP_OBJS        := $(CPP_SRC:%.cpp=$(OBJDIR)/%.o)
AS_OBJS         := $(AS_SRC:%.S=$(OBJDIR)/%.o)

C_DEPS          := $(C_OBJS:%=%.d)
CPP_DEPS        := $(CPP_OBJS:%=%.d)
AS_DEPS         := $(AS_OBJS:%=%.d)

OBJS            := $(C_OBJS) $(CPP_OBJS) $(AS_OBJS)
DEPS            := $(C_DEPS) $(CPP_DEPS) $(AS_DEPS)


hex:  $(PRG).hex
lst:  $(PRG).lst


$(OBJDIR)/$(PRG).elf : $(OBJS)
    $(CC) $(C_FLAGS) $(LD_FLAGS) $^ -o $@

%.lst: $(OBJDIR)/%.elf
    -@rm $@ 2> /dev/nul
    $(OBJDUMP) -h -s -S $< > $@

%.hex: $(OBJDIR)/%.elf
    -@rm $@ 2> /dev/nul
    $(OBJCOPY) -j .text -j .data -O ihex $< $@


$(C_OBJS) : $(OBJDIR)/%.o : %.c Makefile
    $(CC) -MMD -MF [email protected] -c $(C_FLAGS) $(C_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]

$(CPP_OBJS) : $(OBJDIR)/%.o : %.cpp Makefile
    $(CC) -MMD -MF [email protected] -c $(CPP_FLAGS) $(CPP_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]

$(AS_OBJS) : $(OBJDIR)/%.o : %.S Makefile
    $(CC) -MMD -MF [email protected] -c $(AS_FLAGS) $(AS_FLAGS_$(call clear_name,$<)) $< -o $@
    @sed -e 's,.*:,SRC_FILES += ,g' < [email protected] > [email protected]
    @sed -e "\$$s/$$/ $(subst /,\/,$(dir $<))files.mk\n/" < [email protected] >> [email protected]
    @sed -e 's,^[^:]*: *,,' -e 's,^[ \t]*,,' -e 's, \\$$,,' -e 's,$$, :,' < [email protected] >> [email protected]
    -@rm -f [email protected]


clean:
    -@rm -rf $(OBJDIR)/$(PRG).elf
    -@rm -rf $(PRG).lst $(OBJDIR)/$(PRG).map
    -@rm -rf $(PRG).hex $(PRG).bin $(PRG).srec
    -@rm -rf $(PRG)_eeprom.hex $(PRG)_eeprom.bin $(PRG)_eeprom.srec
    -@rm -rf $(MK_DIRS:%=%/*.o) $(MK_DIRS:%=%/*.o.d)
    -@rm -f tags cscope.out

#   -rm -rf $(OBJDIR)/*
#   -rm -rf $(OBJDIR)
#   -rm $(PRG)


tag: tags
tags: $(SRC_FILES)
    if [ -e tags ] ; then ctags -u $? ; else ctags $^ ; fi
    cscope -U -b $^


# include dep. files
ifneq "$(MAKECMDGOALS)" "clean"
-include $(DEPS)
endif


# Create directory
$(shell mkdir $(MK_DIRS) 2>/dev/null)

makef.mk

SAVE_C_SRC := $(C_SRC)
SAVE_CPP_SRC := $(CPP_SRC)
SAVE_AS_SRC := $(AS_SRC)

C_SRC :=
CPP_SRC :=
AS_SRC :=


include $(SRCDIR)/files.mk
MK_DIRS += $(OBJDIR)/$(SRCDIR)


clear_name = $(subst /,_,$(1))


define rename_var
$(2)_$(call clear_name,$(SRCDIR))_$(call clear_name,$(1)) := \
    $($(subst _,,$(2))_$(call clear_name,$(SRCDIR))) $($(call clear_name,$(1)))
$(call clear_name,$(1)) :=
endef


define proc_lang

ORIGIN_SRC_FILES := $($(1)_SRC)

ifneq ($(strip $($(1)_ONLY_FILES)),)
$(1)_SRC := $(filter $($(1)_ONLY_FILES),$($(1)_SRC))
else

ifneq ($(strip $(ONLY_FILES)),)
$(1)_SRC := $(filter $(ONLY_FILES),$($(1)_SRC))
else
$(1)_SRC := $(filter-out $(EXCLUDE_FILES),$($(1)_SRC))
endif

endif

$(1)_ONLY_FILES :=
$(foreach name,$($(1)_SRC),$(eval $(call rename_var,$(name),$(1)_FLAGS)))
$(foreach name,$(ORIGIN_SRC_FILES),$(eval $(call clear_name,$(name)) :=))

endef


$(foreach lang,C CPP AS, $(eval $(call proc_lang,$(lang))))


EXCLUDE_FILES :=
ONLY_FILES :=


SAVE_C_SRC += $(C_SRC:%=$(SRCDIR)/%)
SAVE_CPP_SRC += $(CPP_SRC:%=$(SRCDIR)/%)
SAVE_AS_SRC += $(AS_SRC:%=$(SRCDIR)/%)

C_SRC := $(SAVE_C_SRC)
CPP_SRC := $(SAVE_CPP_SRC)
AS_SRC := $(SAVE_AS_SRC)

./files.mk

C_SRC   := main.c
CPP_SRC :=
AS_SRC  := timer.S

main.c += -DDEBUG

./crc/files.mk

C_SRC    := byte-modbus-crc.c byte-crc8.c
AS_SRC   := modbus-crc.S crc8.S modbus-crc-table.S crc8-table.S

byte-modbus-crc.c += --std=gnu99
byte-crc8.c       += --std=gnu99

Reading JSON from a file?

You can use pandas library to read the JSON file.

import pandas as pd
df = pd.read_json('strings.json',lines=True)
print(df)

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

Right align and left align text in same HTML table cell

Tor Valamo's answer with a little contribution form my side: use the attribute "nowrap" in the "td" element, and you can remove the "width" specification. Hope it helps.

<td nowrap>
  <div style="float:left;">this is left</div>
  <div style="float:right;">this is right</div>
</td>

Difference between thread's context class loader and normal classloader

Each class will use its own classloader to load other classes. So if ClassA.class references ClassB.class then ClassB needs to be on the classpath of the classloader of ClassA, or its parents.

The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC and then passed to a thread owned by ClassLoaderD. In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own classloader.

What is the difference between dynamic programming and greedy approach?

I would like to cite a paragraph which describes the major difference between greedy algorithms and dynamic programming algorithms stated in the book Introduction to Algorithms (3rd edition) by Cormen, Chapter 15.3, page 381:

One major difference between greedy algorithms and dynamic programming is that instead of first finding optimal solutions to subproblems and then making an informed choice, greedy algorithms first make a greedy choice, the choice that looks best at the time, and then solve a resulting subproblem, without bothering to solve all possible related smaller subproblems.

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

If you want examples of Algorithms/Group of Statements with Time complexity as given in the question, here is a small list -

O(1) time

  • Accessing Array Index (int a = ARR[5];)
  • Inserting a node in Linked List
  • Pushing and Poping on Stack
  • Insertion and Removal from Queue
  • Finding out the parent or left/right child of a node in a tree stored in Array
  • Jumping to Next/Previous element in Doubly Linked List

O(n) time

In a nutshell, all Brute Force Algorithms, or Noob ones which require linearity, are based on O(n) time complexity

  • Traversing an array
  • Traversing a linked list
  • Linear Search
  • Deletion of a specific element in a Linked List (Not sorted)
  • Comparing two strings
  • Checking for Palindrome
  • Counting/Bucket Sort and here too you can find a million more such examples....

O(log n) time

  • Binary Search
  • Finding largest/smallest number in a binary search tree
  • Certain Divide and Conquer Algorithms based on Linear functionality
  • Calculating Fibonacci Numbers - Best Method The basic premise here is NOT using the complete data, and reducing the problem size with every iteration

O(n log n) time

The factor of 'log n' is introduced by bringing into consideration Divide and Conquer. Some of these algorithms are the best optimized ones and used frequently.

  • Merge Sort
  • Heap Sort
  • Quick Sort
  • Certain Divide and Conquer Algorithms based on optimizing O(n^2) algorithms

O(n^2) time

These ones are supposed to be the less efficient algorithms if their O(nlogn) counterparts are present. The general application may be Brute Force here.

  • Bubble Sort
  • Insertion Sort
  • Selection Sort
  • Traversing a simple 2D array

jQuery remove all list items from an unordered list

   var ul = document.getElementById("yourElementId");

     while (ul.firstChild)
         ul.removeChild(ul.firstChild);

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

Returning a boolean from a Bash function

I encountered a point (not explictly yet mentioned?) which I was stumbling over. That is, not how to return the boolean, but rather how to correctly evaluate it!

I was trying to say if [ myfunc ]; then ..., but that's simply wrong. You must not use the brackets! if myfunc; then ... is the way to do it.

As at @Bruno and others reiterated, true and false are commands, not values! That's very important to understanding booleans in shell scripts.

In this post, I explained and demoed using boolean variables: https://stackoverflow.com/a/55174008/3220983 . I strongly suggest checking that out, because it's so closely related.

Here, I'll provide some examples of returning and evaluating booleans from functions:

This:

test(){ false; }                                               
if test; then echo "it is"; fi                                 

Produces no echo output. (i.e. false returns false)

test(){ true; }                                                
if test; then echo "it is"; fi                                 

Produces:

it is                                                        

(i.e. true returns true)

And

test(){ x=1; }                                                
if test; then echo "it is"; fi                                 

Produces:

it is                                                                           

Because 0 (i.e. true) was returned implicitly.

Now, this is what was screwing me up...

test(){ true; }                                                
if [ test ]; then echo "it is"; fi                             

Produces:

it is                                                                           

AND

test(){ false; }                                                
if [ test ]; then echo "it is"; fi                             

ALSO produces:

it is                                                                           

Using the brackets here produced a false positive! (I infer the "outer" command result is 0.)

The major take away from my post is: don't use brackets to evaluate a boolean function (or variable) like you would for a typical equality check e.g. if [ x -eq 1 ]; then... !

' << ' operator in verilog

<< is the left-shift operator, as it is in many other languages.

Here RAM_DEPTH will be 1 left-shifted by 8 bits, which is equivalent to 2^8, or 256.

Return a `struct` from a function in C

struct var e2 address pushed as arg to callee stack and values gets assigned there. In fact, get() returns e2's address in eax reg. This works like call by reference.

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

Based on kynan's answer, here are the same aliases, modified so they can handle spaces and initial dashes in filenames:

accept-ours = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --ours -- \"$@\"; git add -u -- \"$@\"; }; f"
accept-theirs = "!f() { [ -z \"$@\" ] && set - '.'; git checkout --theirs -- \"$@\"; git add -u -- \"$@\"; }; f"

Using Get-childitem to get a list of files modified in the last 3 days

I wanted to just add this as a comment to the previous answer, but I can't. I tried Dave Sexton's answer but had problems if the count was 1. This forces an array even if one object is returned.

([System.Object[]](gci c:\pstback\ -Filter *.pst | 
    ? { $_.LastWriteTime -gt (Get-Date).AddDays(-3)})).Count

It still doesn't return zero if empty, but testing '-lt 1' works.

LINQ Where with AND OR condition

from item in db.vw_Dropship_OrderItems
    where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
    (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
    select item;

Might give strange behavior if both listMerchants and listStatus are both null.

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

Can git undo a checkout of unstaged files

In VSCODE ctrl+z (undo) worked for me

I did git checkout .instead of git add . and all my file changes were lost.

But Now using command + z in my mac , recovered the changes and saved a tone of work for me.

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

Loop through an array of strings in Bash?

Implicit array for script or functions:

In addition to anubhava's correct answer: If basic syntax for loop is:

for var in "${arr[@]}" ;do ...$var... ;done

there is a special case in :

When running a script or a function, arguments passed at command lines will be assigned to $@ array variable, you can access by $1, $2, $3, and so on.

This can be populated (for test) by

set -- arg1 arg2 arg3 ...

A loop over this array could be written simply:

for item ;do
    echo "This is item: $item."
  done

Note that the reserved work in is not present and no array name too!

Sample:

set -- arg1 arg2 arg3 ...
for item ;do
    echo "This is item: $item."
  done
This is item: arg1.
This is item: arg2.
This is item: arg3.
This is item: ....

Note that this is same than

for item in "$@";do
    echo "This is item: $item."
  done

Then into a script:

#!/bin/bash

for item ;do
    printf "Doing something with '%s'.\n" "$item"
  done

Save this in a script myscript.sh, chmod +x myscript.sh, then

./myscript.sh arg1 arg2 arg3 ...
Doing something with 'arg1'.
Doing something with 'arg2'.
Doing something with 'arg3'.
Doing something with '...'.

Same in a function:

myfunc() { for item;do cat <<<"Working about '$item'."; done ; }

Then

myfunc item1 tiem2 time3
Working about 'item1'.
Working about 'tiem2'.
Working about 'time3'.

How to get a tab character?

Sure there's an entity for tabs:

&#9;

(The tab is ASCII character 9, or Unicode U+0009.)

However, just like literal tabs (ones you type in to your text editor), all tab characters are treated as whitespace by HTML parsers and collapsed into a single space except those within a <pre> block, where literal tabs will be rendered as 8 spaces in a monospace font.

Validating input using java.util.Scanner

Overview of Scanner.hasNextXXX methods

java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:

Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.

The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.


Example 1: Validating positive ints

Here's a simple example of using hasNextInt() to validate positive int from the input.

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a positive number!");
    while (!sc.hasNextInt()) {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);

Here's an example session:

Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5

Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.

Related questions


Example 2: Multiple hasNextXXX on the same token

Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!

This has two consequences:

  • If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
  • If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!

Here's an example of performing multiple hasNextXXX tests.

Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
    System.out.println(
        sc.hasNextInt() ? "(int) " + sc.nextInt() :
        sc.hasNextLong() ? "(long) " + sc.nextLong() :  
        sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
        sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
        "(String) " + sc.next()
    );
}

Here's an example session:

5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit

Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.


Example 3 : Validating vowels

Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
    System.out.println("That's not a vowel!");
    sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);

Here's an example session:

Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e

In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.

API links

Related questions

References


Example 4: Using two Scanner at once

Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:

Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
    Scanner lineSc = new Scanner(sc.nextLine());
    int sum = 0;
    while (lineSc.hasNextInt()) {
        sum += lineSc.nextInt();
    }
    System.out.println("Sum is " + sum);
}

Here's an example session:

Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit

In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.


Summary

  • Scanner provides a rich set of features, such as hasNextXXX methods for validation.
  • Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
  • Always remember that hasNextXXX does not advance the Scanner past any input.
  • Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
  • Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
    • Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.

Where should I put <script> tags in HTML markup?

The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document body so they don't block rendering of the page.

But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:

There are some great slides by Steve Souders (client-side performance expert) about:

  • Different techniques to load external JavaScript files in parallel
  • their effect on loading time and page rendering
  • what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).

How can I output a UTF-8 CSV in PHP that Excel will read properly?

Here is how I did it (that's to prompt browser to download the csv file):

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=file.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
echo $csv_file_content;
exit();

The only thing it fixed UTF8 encoding problem in CSV preview when you hit space bar on Mac.. but not in Excel Mac 2008... don't know why

C++ printing boolean, what is displayed?

0 will get printed.

As in C++ true refers to 1 and false refers to 0.

In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.

#include <iostream>
int main()
{
  std::cout << std::boolalpha << false << std::endl;
}

output:

false

IDEONE

How to clear File Input

This works to

 $("#yourINPUTfile").val("");

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Or just use this in your View(Razor page)

@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))

I recommend that don't add date format in your model class

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

when your URL pattern is wrong, this error may be occurred.

eg. If you wrote @WebServlet("login"), this error will be shown. The correct one is @WebServlet("/login").

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

How to input a regex in string.replace?

I would go like this (regex explained in comments):

import re

# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")

# <\/{0,}\[\d+>
# 
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»

subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>"""

result = pattern.sub("", subject)

print(result)

If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.

Stop node.js program from command line

For MacOS

  1. Open terminal
  2. Run the below code and hit enter

     sudo kill $(sudo lsof -t -i:4200)
    

Explain ggplot2 warning: "Removed k rows containing missing values"

I ran into this as well, but in the case where I wanted to avoid the extra error messages while keeping the range provided. An option is also to subset the data prior to setting the range, so that the range can be kept however you like without triggering warnings.

library(ggplot2)

range(mtcars$hp)
#> [1]  52 335

# Setting limits with scale_y_continous (or ylim) and subsetting accordingly
## avoid warning messages about removing data
ggplot(data= subset(mtcars, hp<=300 & hp >= 100), aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(100,300))

PreparedStatement IN clause alternatives?

An unpleasant work-around, but certainly feasible is to use a nested query. Create a temporary table MYVALUES with a column in it. Insert your list of values into the MYVALUES table. Then execute

select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )

Ugly, but a viable alternative if your list of values is very large.

This technique has the added advantage of potentially better query plans from the optimizer (check a page for multiple values, tablescan only once instead once per value, etc) may save on overhead if your database doesn't cache prepared statements. Your "INSERTS" would need to be done in batch and the MYVALUES table may need to be tweaked to have minimal locking or other high-overhead protections.

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

Print debugging info from stored procedure in MySQL

One workaround is just to use select without any other clauses.

http://lists.mysql.com/mysql/197901

How can I execute PHP code from the command line?

If you're using Laravel, you can use php artisan tinker to get an amazing interactive shell to interact with your Laravel app. However, Tinker works with "Psysh" under the hood which is a popular PHP REPL and you can use it even if you're not using Laravel (bare PHP):

// Bare PHP:
>>> preg_match("/hell/", "hello");
=> 1

// Laravel Stuff:
>>> Str::slug("How to get the job done?!!?!", "_");
=> "how_to_get_the_job_done"

One great feature I really like about Psysh is that it provides a quick way for directly looking up the PHP docs from the command line. To get it to work, you only have to take the following simple steps:

apt install php-sqlite3

And then get the required PHP documentation database and move it to the proper location:

wget http://psysh.org/manual/en/php_manual.sqlite
mkdir -p /usr/local/share/psysh/ && mv php_manual.sqlite /usr/local/share/psysh/

Now for instance:

Enter image description here

How can I add a variable to console.log?

You can use the backslash to include both the story and the players name in one line.

var name=prompt("what is your name?"); console.log("story"\name\"story");

Python: SyntaxError: non-keyword after keyword arg

It's just what it says:

inputFile = open((x), encoding = "utf8", "r")

You have specified encoding as a keyword argument, but "r" as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:

inputFile = open((x), "r", encoding = "utf8")

Switch php versions on commandline ubuntu 16.04

May be you might have an old PHP version like PHP 5.6 in your system and you installed PHP 7.2 too so thats multiple PHP in your machine. There are some applications which were developed when older PHP 5.6 was latest version, they are still live and you working on those applications, You might be working on Laravel simultaneously but Laravel requires PHP 7+ to get started. Getting the picture ?

In that case you can switch between the PHP versions to suit your requirements.

Switch From PHP 5.6 => PHP 7.2

Apache:-

sudo a2dismod php5.6
sudo a2enmod php7.2
sudo service apache2 restart

Command Line:-

sudo update-alternatives --set php /usr/bin/php7.2
sudo update-alternatives --set phar /usr/bin/phar7.2
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.2
sudo update-alternatives --set phpize /usr/bin/phpize7.2
sudo update-alternatives --set php-config /usr/bin/php-config7.2

And vice-versa, Switch From PHP 7.2 => PHP 5.6

Apache:-

sudo a2dismod php7.2
sudo a2enmod php5.6
sudo service apache2 restart

Command Line:-

sudo update-alternatives --set php /usr/bin/php5.6
sudo update-alternatives --set phar /usr/bin/phar5.6
sudo update-alternatives --set phar.phar /usr/bin/phar.phar5.6
sudo update-alternatives --set phpize /usr/bin/phpize5.6
sudo update-alternatives --set php-config /usr/bin/php-config5.6

How to use a typescript enum value in an Angular2 ngSwitch statement

Start by considering 'Do I really want to do this?'

I have no problem referring to enums directly in HTML, but in some cases there are cleaner alternatives that don't lose type-safe-ness. For instance if you choose the approach shown in my other answer, you may have declared TT in your component something like this:

public TT = 
{
    // Enum defines (Horizontal | Vertical)
    FeatureBoxResponsiveLayout: FeatureBoxResponsiveLayout   
}

To show a different layout in your HTML, you'd have an *ngIf for each layout type, and you could refer directly to the enum in your component's HTML:

*ngIf="(featureBoxResponsiveService.layout | async) == TT.FeatureBoxResponsiveLayout.Horizontal"

This example uses a service to get the current layout, runs it through the async pipe and then compares it to our enum value. It's pretty verbose, convoluted and not much fun to look at. It also exposes the name of the enum, which itself may be overly verbose.

Alternative, that retains type safety from the HTML

Alternatively you can do the following, and declare a more readable function in your component's .ts file :

*ngIf="isResponsiveLayout('Horizontal')"

Much cleaner! But what if someone types in 'Horziontal' by mistake? The whole reason you wanted to use an enum in the HTML was to be typesafe right?

We can still achieve that with keyof and some typescript magic. This is the definition of the function:

isResponsiveLayout(value: keyof typeof FeatureBoxResponsiveLayout)
{
    return FeatureBoxResponsiveLayout[value] == this.featureBoxResponsiveService.layout.value;
}

Note the usage of FeatureBoxResponsiveLayout[string] which converts the string value passed in to the numeric value of the enum.

This will give an error message with an AOT compilation if you use an invalid value.

Argument of type '"H4orizontal"' is not assignable to parameter of type '"Vertical" | "Horizontal"

Currently VSCode isn't smart enough to underline H4orizontal in the HTML editor, but you'll get the warning at compile time (with --prod build or --aot switch). This also may be improved upon in a future update.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.

Sub UploadData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim myWb as Excel.Workbook

    Set myWb = ActiveWorkbook
    Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
    xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
    xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text

    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).

Return positions of a regex match() in Javascript?

_x000D_
_x000D_
var str = 'my string here';

var index = str.match(/hre/).index;

alert(index); // <- 10
_x000D_
_x000D_
_x000D_

Solving "adb server version doesn't match this client" error

I've recently had this issue too and after none of the answers on here worked I realised that the APK I was testing against would have been built against the latest sdk.

So I went into the Appium settings and changed the platform version to the latest version and this resolved the issue for me.

Using await outside of an async function

Top level await is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.

There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:

// data.js
const data = await fetch( '/data.json' );
export default data;

Now any file that imports data.js won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.

My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.

What does "implements" do on a class?

An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.

I guess the poster assumes a certain level of knowledge about the language.

Required maven dependencies for Apache POI to work

For an excel writer you might need the following:

            <dependency>
              <groupId>org.apache.poi</groupId>
              <artifactId>poi</artifactId>
              <version>3.10-FINAL</version>
           </dependency>


        <dependency>
             <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${apache.poi.version}</version>
       </dependency>

count (non-blank) lines-of-code in bash

The neatest command is

grep -vc ^$ fileName

with -c option, you don't even need wc -l

Rails 4 - Strong Parameters - Nested Objects

As odd as it sound when you want to permit nested attributes you do specify the attributes of nested object within an array. In your case it would be

Update as suggested by @RafaelOliveira

params.require(:measurement)
      .permit(:name, :groundtruth => [:type, :coordinates => []])

On the other hand if you want nested of multiple objects then you wrap it inside a hash… like this

params.require(:foo).permit(:bar, {:baz => [:x, :y]})


Rails actually have pretty good documentation on this: http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit

For further clarification, you could look at the implementation of permit and strong_parameters itself: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb#L246-L247

How to get the difference between two arrays in JavaScript?

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
var diff = [];
for (var i in a2) {
   var found = false;
   for (var j in a1) {
      if (a2[i] === a1[j]) found = true;
   }
   if (found === false) diff.push(a2[i]);
}

That simple. Could use with objects also, checking one property of object. Like,

if (a2[i].id === a1[j].id) found = true;

How To Get Selected Value From UIPickerView

This is what I did:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    selectedEntry = [allEntries objectAtIndex:row];

}

The selectedEntry is a NSString and will hold the currently selected entry in the pickerview. I am new to objective C but I think this is much easier.

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Try

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

A value of '*' will match anything; in this case you are responsible to provide your own validation of the Host header.

How do I access (read, write) Google Sheets spreadsheets with Python?

(Jun-Dec 2016) Most answers here are now out-of-date as: 1) GData APIs are the previous generation of Google APIs, and that's why it was hard for @Josh Brown to find that old GData Docs API documentation. While not all GData APIs have been deprecated, all newer Google APIs do not use the Google Data protocol; and 2) Google released a new Google Sheets API (not GData). In order to use the new API, you need to get the Google APIs Client Library for Python (it's as easy as pip install -U google-api-python-client [or pip3 for Python 3]) and use the latest Sheets API v4+, which is much more powerful & flexible than older API releases.

Here's one code sample from the official docs to help get you kickstarted. However, here are slightly longer, more "real-world" examples of using the API you can learn from (videos plus blog posts):

The latest Sheets API provides features not available in older releases, namely giving developers programmatic access to a Sheet as if you were using the user interface (create frozen rows, perform cell formatting, resizing rows/columns, adding pivot tables, creating charts, etc.), but NOT as if it was some database that you could perform searches on and get selected rows from. You'd basically have to build a querying layer on top of the API that does this. One alternative is to use the Google Charts Visualization API query language, which does support SQL-like querying. You can also query from within the Sheet itself. Be aware that this functionality existed before the v4 API, and that the security model was updated in Aug 2016. To learn more, check my G+ reshare to a full write-up from a Google Developer Expert.

Also note that the Sheets API is primarily for programmatically accessing spreadsheet operations & functionality as described above, but to perform file-level access such as imports/exports, copy, move, rename, etc., use the Google Drive API instead. Examples of using the Drive API:

(*) - TL;DR: upload plain text file to Drive, import/convert to Google Docs format, then export that Doc as PDF. Post above uses Drive API v2; this follow-up post describes migrating it to Drive API v3, and here's a developer video combining both "poor man's converter" posts.

To learn more about how to use Google APIs with Python in general, check out my blog as well as a variety of Google developer videos (series 1 and series 2) I'm producing.

ps. As far as Google Docs goes, there isn't a REST API available at this time, so the only way to programmatically access a Doc is by using Google Apps Script (which like Node.js is JavaScript outside of the browser, but instead of running on a Node server, these apps run in Google's cloud; also check out my intro video.) With Apps Script, you can build a Docs app or an add-on for Docs (and other things like Sheets & Forms).

UPDATE Jul 2018: The above "ps." is no longer true. The G Suite developer team pre-announced a new Google Docs REST API at Google Cloud NEXT '18. Developers interested in getting into the early access program for the new API should register at https://developers.google.com/docs.

UPDATE Feb 2019: The Docs API launched to preview last July is now available generally to all... read the launch post for more details.

UPDATE Nov 2019: In an effort to bring G Suite and GCP APIs more inline with each other, earlier this year, all G Suite code samples were partially integrated with GCP's newer (lower-level not product) Python client libraries. The way auth is done is similar but (currently) requires a tiny bit more code to manage token storage, meaning rather than our libraries manage storage.json, you'll store them using pickle (token.pickle or whatever name you prefer) instead, or choose your own form of persistent storage. For you readers here, take a look at the updated Python quickstart example.

Override browser form-filling and input highlighting with HTML/CSS

Since the browser searches for password type fields, another workaround is to include a hidden field at the beginning of your form:

<!-- unused field to stop browsers from overriding form style -->
<input type='password' style = 'display:none' />

AngularJS passing data to $http.get request

For sending get request with parameter i use

  $http.get('urlPartOne\\'+parameter+'\\urlPartTwo')

By this you can use your own url string

How to convert all text to lowercase in Vim

  • Toggle case "HellO" to "hELLo" with g~ then a movement.
  • Uppercase "HellO" to "HELLO" with gU then a movement.
  • Lowercase "HellO" to "hello" with gu then a movement.

For examples and more info please read this: http://vim.wikia.com/wiki/Switching_case_of_characters

checking if a number is divisible by 6 PHP

$num += (6-$num%6)%6;

no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.

python: SyntaxError: EOL while scanning string literal

In my case, I forgot (' or ") at the end of string. E.g 'ABC' or "ABC"

Git merge error "commit is not possible because you have unmerged files"

You can use git stash to save the current repository before doing the commit you want to make (after merging the changes from the upstream repo with git stash pop). I had to do this yesterday when I had the same problem.

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

window.onload vs document.onload

window.onload however they are often the same thing. Similarly body.onload becomes window.onload in IE.

Which data type for latitude and longitude?

You can use the data type point - combines (x,y) which can be your lat / long. Occupies 16 bytes: 2 float8 numbers internally.

Or make it two columns of type float (= float8 or double precision). 8 bytes each.
Or real (= float4) if additional precision is not needed. 4 bytes each.
Or even numeric if you need absolute precision. 2 bytes for each group of 4 digits, plus 3 - 8 bytes overhead.

Read the fine manual about numeric types and geometric types.


The geometry and geography data types are provided by the additional module PostGIS and occupy one column in your table. Each occupies 32 bytes for a point. There is some additional overhead like an SRID in there. These types store (long/lat), not (lat/long).

Start reading the PostGIS manual here.

Format an Excel column (or cell) as Text in C#?

Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

Disclaimer: I own SpreadsheetGear LLC

How do I enable EF migrations for multiple contexts to separate databases?

If more databases exist use following codes in PowerShell

Add-Migration Starter -context EnrollmentAppContext 
  • 'Starter' is Migration Name

  • 'EnrollmentAppContext' is name of my app Context

You can open PowerShell in VS by doing: Tools->NuGet Package Manager->Package Manager Console

Vue js error: Component template should contain exactly one root element

Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

The right approach is

<template>
  <div> <!-- The root -->
    <p></p> 
    <p></p>
  </div>
</template>

The wrong approach

<template> <!-- No root Element -->
    <p></p> 
    <p></p>
</template>

Multi Root Components

The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.

As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.

Here is how you can create a simple functional component.

Vue.component('my-component', {
    // you must set functional as true
  functional: true,
  // Props are optional
  props: {
    // ...
  },
  // To compensate for the lack of an instance,
  // we are now provided a 2nd context argument.
  render: function (createElement, context) {
    // ...
  }
})

Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.

<template>
 <ul>
     <NavBarRoutes :routes="persistentNavRoutes"/>
     <NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
     <NavBarRoutes v-else :routes="loggedOutNavRoutes" />
 </ul>
</template>

Now if we take a look at NavBarRoutes template

<template>
 <li
 v-for="route in routes"
 :key="route.name"
 >
 <router-link :to="route">
 {{ route.title }}
 </router-link>
 </li>
</template>

We cant do some thing like this we will be violating single root component restriction

Solution Make this component functional and use render

{
functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  <li key={route.name}>
    <router-link to={route}>
      {route.title}
    </router-link>
  </li>
 )
}

Here you have it you have created a multi root component, Happy coding

Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/

Allow user to select camera or gallery for image

You'll have to create your own chooser dialog merging both intent resolution results.

To do this, you will need to query the PackageManager with PackageManager.queryIntentActivities() for both original intents and create the final list of possible Intents with one new Intent for each retrieved activity like this:

List<Intent> yourIntentsList = new ArrayList<Intent>();

List<ResolveInfo> listCam = packageManager.queryIntentActivities(camIntent, 0);
for (ResolveInfo res : listCam) {
    final Intent finalIntent = new Intent(camIntent);
    finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
    yourIntentsList.add(finalIntent);
}

List<ResolveInfo> listGall = packageManager.queryIntentActivities(gallIntent, 0);
for (ResolveInfo res : listGall) {
    final Intent finalIntent = new Intent(gallIntent);
    finalIntent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
    yourIntentsList.add(finalIntent);
}

(I wrote this directly here so this may not compile)

Then, for more info on creating a custom dialog from a list see https://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog

What do the makefile symbols $@ and $< mean?

in exemple if you want to compile sources but have objects in an different directory :

You need to do :

gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...

but with most of macros the result will be all objects followed by all sources, like :

gcc -c -o <all OBJ path> <all SRC path>

so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(

the solution is to use these special macros

$@ $<

this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)

$(OBJ):$(SRC)
   gcc -c -o $@ $< $(HEADERS) $(FLAGS)

it means :

    $@ = $(OBJ)
    $< = $(SRC)

but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC

How do I display image in Alert/confirm box in Javascript?

Snarky yet potentially useful answer: http://picascii.com/ (currently down)

https://www.ascii-art-generator.org/es.html (don't forget to put a \n after each line!)

Pretty printing XML with javascript

From the text of the question I get the impression that a string result is expected, as opposed to an HTML-formatted result.

If this is so, the simplest way to achieve this is to process the XML document with the identity transformation and with an <xsl:output indent="yes"/> instruction:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When applying this transformation on the provided XML document:

<root><node/></root>

most XSLT processors (.NET XslCompiledTransform, Saxon 6.5.4 and Saxon 9.0.0.2, AltovaXML) produce the wanted result:

<root>
  <node />
</root>

How can I create a carriage return in my C# string

Along with Environment.NewLine and the literal \r\n or just \n you may also use a verbatim string in C#. These begin with @ and can have embedded newlines. The only thing to keep in mind is that " needs to be escaped as "". An example:

string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."

How to read files from resources folder in Scala?

For Scala 2.11, if getLines doesn't do exactly what you want you can also copy the a file out of the jar to the local file system.

Here's a snippit that reads a binary google .p12 format API key from /resources, writes it to /tmp, and then uses the file path string as an input to a spark-google-spreadsheets write.

In the world of sbt-native-packager and sbt-assembly, copying to local is also useful with scalatest binary file tests. Just pop them out of resources to local, run the tests, and then delete.

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

Global javascript variable inside document.ready

Use window.intro inside of $(document).ready().

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

How to resize an image to a specific size in OpenCV?

You can use CvInvoke.Resize for Emgu.CV 3.0

e.g

CvInvoke.Resize(inputImage, outputImage, new System.Drawing.Size(100, 100), 0, 0, Inter.Cubic);

Details are here

How can I move HEAD back to a previous location? (Detached head) & Undo commits

This may not be a technical solution, but it works. (if anyone of your teammate has the same branch in local)

Let's assume your branch name as branch-xxx.

Steps to Solve:

  • Don't do update or pull - nothing
  • Just create a new branch (branch-yyy) from branch-xxx on his machine
  • That's all, all your existing changes will be in this new branch (branch-yyy). You can continue your work with this branch.

Note: Again, this is not a technical solution, but it will help for sure.

Android - Handle "Enter" in an EditText

   final EditText edittext = (EditText) findViewById(R.id.edittext);
    edittext.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {
                // Perform action on key press
                Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    });

How can I concatenate two arrays in Java?

Here a possible implementation in working code of the pseudo code solution written by silvertab.

Thanks silvertab!

public class Array {

   public static <T> T[] concat(T[] a, T[] b, ArrayBuilderI<T> builder) {
      T[] c = builder.build(a.length + b.length);
      System.arraycopy(a, 0, c, 0, a.length);
      System.arraycopy(b, 0, c, a.length, b.length);
      return c;
   }
}

Following next is the builder interface.

Note: A builder is necessary because in java it is not possible to do

new T[size]

due to generic type erasure:

public interface ArrayBuilderI<T> {

   public T[] build(int size);
}

Here a concrete builder implementing the interface, building a Integer array:

public class IntegerArrayBuilder implements ArrayBuilderI<Integer> {

   @Override
   public Integer[] build(int size) {
      return new Integer[size];
   }
}

And finally the application / test:

@Test
public class ArrayTest {

   public void array_concatenation() {
      Integer a[] = new Integer[]{0,1};
      Integer b[] = new Integer[]{2,3};
      Integer c[] = Array.concat(a, b, new IntegerArrayBuilder());
      assertEquals(4, c.length);
      assertEquals(0, (int)c[0]);
      assertEquals(1, (int)c[1]);
      assertEquals(2, (int)c[2]);
      assertEquals(3, (int)c[3]);
   }
}

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

git pull error "The requested URL returned error: 503 while accessing"

Try disabling all the system wide HTTP and HTTPS proxies:

export http_proxy="" 
export https_proxy=""
export HTTP_PROXY=""
export HTTPS_PROXY=""

psql: FATAL: database "<user>" does not exist

Try using-

psql -d postgres

I was also facing the same issue when I ran psql

"unexpected token import" in Nodejs5 and babel?

Until modules are implemented you can use the Babel "transpiler" to run your code:

npm install --save babel-cli babel-preset-node6

and then

./node_modules/babel-cli/bin/babel-node.js --presets node6 ./your_script.js

If you dont want to type --presets node6 you can save it .babelrc file by:

{
  "presets": [
    "node6"
  ]
}

See https://www.npmjs.com/package/babel-preset-node6 and https://babeljs.io/docs/usage/cli/

How to send file contents as body entity using cURL

In my case, @ caused some sort of encoding problem, I still prefer my old way:

curl -d "$(cat /path/to/file)" https://example.com

How do I keep CSS floats in one line?

Another option: Do not float your right column; just give it a left margin to move it beyond the float. You'll need a hack or two to fix IE6, but that's the basic idea.

How to set environment variables in PyCharm?

You can set environmental variables in Pycharm's run configurations menu.

  1. Open the Run Configuration selector in the top-right and cick Edit Configurations...

    Edit Configurations...

  2. Find Environmental variables and click ...

    Environmental variables

  3. Add or change variables, then click OK

    Editing environmental variables

You can access your environmental variables with os.environ

import os
print(os.environ['SOME_VAR'])

Clear dropdownlist with JQuery

I tried both .empty() as well as .remove() for my dropdown and both were slow. Since I had almost 4,000 options there.

I used .html("") which is much faster in my condition.
Which is below

  $(dropdown).html("");

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

I think you can adapt the function to substract the two timestamps:

return  EXTRACT(MINUTE FROM 
  TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
  TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);

I think you could simplify it by just using CAST(p_date as TIMESTAMP).

return  EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));

Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.

What is the purpose of the : (colon) GNU Bash builtin?

Historically, Bourne shells didn't have true and false as built-in commands. true was instead simply aliased to :, and false to something like let 0.

: is slightly better than true for portability to ancient Bourne-derived shells. As a simple example, consider having neither the ! pipeline operator nor the || list operator (as was the case for some ancient Bourne shells). This leaves the else clause of the if statement as the only means for branching based on exit status:

if command; then :; else ...; fi

Since if requires a non-empty then clause and comments don't count as non-empty, : serves as a no-op.

Nowadays (that is: in a modern context) you can usually use either : or true. Both are specified by POSIX, and some find true easier to read. However there is one interesting difference: : is a so-called POSIX special built-in, whereas true is a regular built-in.

  • Special built-ins are required to be built into the shell; Regular built-ins are only "typically" built in, but it isn't strictly guaranteed. There usually shouldn't be a regular program named : with the function of true in PATH of most systems.

  • Probably the most crucial difference is that with special built-ins, any variable set by the built-in - even in the environment during simple command evaluation - persists after the command completes, as demonstrated here using ksh93:

    $ unset x; ( x=hi :; echo "$x" )
    hi
    $ ( x=hi true; echo "$x" )
    
    $
    

    Note that Zsh ignores this requirement, as does GNU Bash except when operating in POSIX compatibility mode, but all other major "POSIX sh derived" shells observe this including dash, ksh93, and mksh.

  • Another difference is that regular built-ins must be compatible with exec - demonstrated here using Bash:

    $ ( exec : )
    -bash: exec: :: not found
    $ ( exec true )
    $
    
  • POSIX also explicitly notes that : may be faster than true, though this is of course an implementation-specific detail.

firefox proxy settings via command line

cd /D "%APPDATA%\Mozilla\Firefox\Profiles" cd *.default set ffile=%cd% echo user_pref("network.proxy.http", "%1");>>"%ffile%\prefs.js" echo user_pref("network.proxy.http_port", 3128);>>"%ffile%\prefs.js" echo user_pref("network.proxy.type", 1);>>"%ffile%\prefs.js" set ffile= cd %windir%

This is nice ! Thanks for writing this. I needed this exact piece of code for Windows. My goal was to do this by learning to do it with Linux first and then learn the Windows shell which I was not happy about having to do so you saved me some time!

My Linux version is at the bottom of this post. I've been experimenting with which file to insert the prefs into. It seems picky. First I tried in ~/.mozilla/firefox/*.default/prefs.js but it didn't load very well. The about:config screen never showed my changes. Currently I've been trying to edit the actual Firefox defaults file. If someone has the knowledge off the top of their head could they rewrite the Windows code to only add the lines if they're not already in there? I have no idead how to do sed/awk stuff in Windows without installing Cygwin first.

The only change I was able to make to the Windows scripts is above in the quoted part. I change the IP to %1 so when you call the script from the command line you can give it an option instead of having to change the file.

#!/bin/bash
version="`firefox -v | awk '{print substr($3,1,3)}'`"
echo $version " is the version."
# Insert an ip into firefox for the proxy if there isn't one
if
! grep network.proxy.http /etc/firefox-$version/pref/firefox.js 
  then echo 'pref("network.proxy.http", "'"$1"'")";' >> /etc/firefox-$version/pref/firefox.js 
fi

# Even if there is change it to what we want
sed -i s/^.*network.proxy.http\".*$/'pref("network.proxy.http", "'"$1"')";'/  /etc/firefox-$version/pref/firefox.js 

# Set the port
if ! grep network.proxy.http_port /etc/firefox-$version/pref/firefox.js 
  then echo 'pref("network.proxy.http_port", 9980);' >> /etc/firefox-$version/pref/firefox.js 
  else sed -i s/^.*network.proxy.http_port.*$/'pref("network.proxy.http_port", 9980);'/ /etc/firefox-$version/pref/firefox.js 
fi

# Turn on the proxy
if ! grep network.proxy.type  /etc/firefox-$version/pref/firefox.js 
  then echo 'pref("network.proxy.type", 1);' >> /etc/firefox-$version/pref/firefox.js 
  else sed -i s/^.*network.proxy.type.*$/'pref("network.proxy.type", 1)";'/ /etc/firefox-$version/pref/firefox.js 
fi

Put request with simple string as request body

Have you tried the following:

axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
    .then(function(response){
        console.log('saved successfully')
});

Reference: http://codeheaven.io/how-to-use-axios-as-your-http-client/

jquery validate check at least one checkbox

make sure the input-name[] is in inverted commas in the ruleset. Took me hours to figure that part out.

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

read more here... http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29

How to get the row number from a datatable?

You have two options here.

  1. You can create your own index counter and increment it
  2. Rather than using a foreach loop, you can use a for loop

The individual row simply represents data, so it will not know what row it is located in.

AngularJS - How to use $routeParams in generating the templateUrl?

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

PHP json_encode json_decode UTF-8

if you get "unexpected Character" error you should check if there is a BOM (Byte Order Marker saved into your utf-8 json. You can either remove the first character or save if without BOM.

Replacing &nbsp; from javascript dom text node

That first line is pretty messed up. It only needs to be:

var cleanText = text.replace(/\xA0/g,' ');

That should be all you need.

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

The error is try to fix a Youtube error.

The solution to avoid your Javascript-Console-Error complex is to accept that Youtube (and also other webpages) can have Javascript errors that you can't fix.

That is all.

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

Usage of __slots__?

Quoting Jacob Hallen:

The proper use of __slots__ is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. [This use of __slots__ eliminates the overhead of one dict for every object.] While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.

Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.

Making CPython smart enough to handle saving space without __slots__ is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

changing name of /bootstrap/cache/config.php to config.php.old doesn't work for me neither clearing cache with the commands artisan

  1. php artisan config:clear
  2. php artisan cache:clear
  3. php artisan config:cache

And for some weird reason I can't change permission for the owner on the directories, so my solution was running my IDE (Visual Studio Code) as admin, and everything works.

My project is in an F:/ path of another disk.

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

How can I get my Android device country code without using GPS?

You shouldn't be passing anything in to getCountry(). Remove Locale.getDefault():

String locale = context.getResources().getConfiguration().locale.getCountry();

mysql Foreign key constraint is incorrectly formed error

I ran into this same problem with HeidiSQL. The error you receive is very cryptic. My problem ended up being that the foreign key column and the referencing column were not of the same type or length.

The foreign key column was SMALLINT(5) UNSIGNED and the referenced column was INT(10) UNSIGNED. Once I made them both the same exact type, the foreign key creation worked perfectly.

Programmatically select a row in JTable

You can do it calling setRowSelectionInterval :

table.setRowSelectionInterval(0, 0);

to select the first row.

How to convert from Hex to ASCII in JavaScript?

Another way to do it (if you use Node.js):

var input  = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output);  // Result: 32343630 -> 2460

How to loop through a collection that supports IEnumerable?

Along with the already suggested methods of using a foreach loop, I thought I'd also mention that any object that implements IEnumerable also provides an IEnumerator interface via the GetEnumerator method. Although this method is usually not necessary, this can be used for manually iterating over collections, and is particularly useful when writing your own extension methods for collections.

IEnumerable<T> mySequence;
using (var sequenceEnum = mySequence.GetEnumerator())
{
    while (sequenceEnum.MoveNext())
    {
        // Do something with sequenceEnum.Current.
    }
}

A prime example is when you want to iterate over two sequences concurrently, which is not possible with a foreach loop.

How to strip HTML tags from a string in SQL Server?

While Arvin Amir's answer comes close to a full one-line solution you can drop in anywhere; he's got a slight bug in his select statement (missing the end of the line), and I wanted to handle the most common character references.

What I ended up doing was this:

SELECT replace(replace(replace(CAST(CAST(replace([columnNameHere], '&', '&amp;') as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max)), '&amp;', '&'), '&nbsp;', ' '), '&#x20;', ' ')
FROM [tableName]

Without the character reference code it can be simplified to this:

SELECT CAST(CAST([columnNameHere] as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max))
FROM [tableName]

Can't import Numpy in Python

Disabling pyright worked perfectly for me on VS.

How to move files from one git repo to another (not a clone), preserving history

In my case, I didn't need to preserve the repo I was migrating from or preserve any previous history. I had a patch of the same branch, from a different remote

#Source directory
git remote rm origin
#Target directory
git remote add branch-name-from-old-repo ../source_directory

In those two steps, I was able to get the other repo's branch to appear in the same repo.

Finally, I set this branch (that I imported from the other repo) to follow the target repo's mainline (so I could diff them accurately)

git br --set-upstream-to=origin/mainline

Now it behaved as-if it was just another branch I had pushed against that same repo.

How to get current working directory in Java?

File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());

Prints something like:

/path/to/current/directory
/path/to/current/directory/.

Note that File.getCanonicalPath() throws a checked IOException but it will remove things like ../../../

Convert date field into text in Excel

You can use TEXT like this as part of a concatenation

=TEXT(A1,"dd-mmm-yy") & " other string"

enter image description here

How to Add Incremental Numbers to a New Column Using Pandas

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

How to show a GUI message box from a bash script in linux?

I believe Zenity will do what you want. It's specifically designed for displaying GTK dialogs from the command line, and it's available as an Ubuntu package.

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

JavaScript calculate the day of the year (1 - 366)

I wrote these two javascript functions which return the day of the year (Jan 1 = 1). Both of them account for leap years.

function dayOfTheYear() {
// for today
var M=[31,28,31,30,31,30,31,31,30,31,30,31]; var x=new Date(); var m=x.getMonth();
var y=x.getFullYear(); if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {++M[1];}
var Y=0; for (var i=0;i<m;++i) {Y+=M[i];}
return Y+x.getDate();
}

function dayOfTheYear2(m,d,y) {
// for any day : m is 1 to 12, d is 1 to 31, y is a 4-digit year
var m,d,y; var M=[31,28,31,30,31,30,31,31,30,31,30,31];
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {++M[1];}
var Y=0; for (var i=0;i<m-1;++i) {Y+=M[i];}
return Y+d;
}

Press Enter to move to next control

Tab as Enter: create a user control which inherits textbox, override the KeyPress method. If the user presses enter you can either call SendKeys.Send("{TAB}") or System.Windows.Forms.Control.SelectNextControl(). Note you can achieve the same using the KeyPress event.

Focus Entire text: Again, via override or events, target the GotFocus event and then call TextBox.Select method.

Accessing an SQLite Database in Swift

Yet another SQLite wrapper for Swift 2 and Swift 3: http://github.com/groue/GRDB.swift

Features:

  • An API that will look familiar to users of ccgus/fmdb

  • A low-level SQLite API that leverages the Swift standard library

  • A pretty Swift query interface for SQL-allergic developers

  • Support for the SQLite WAL mode, and concurrent database access for extra performance

  • A Record class that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations

  • Swift type freedom: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.

  • Database Migrations

  • Speed: https://github.com/groue/GRDB.swift/wiki/Performance

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

If after all these tips, the thumbnail is still not showing, try this:

My problem was that the double quotes from the og attributes were being removed when built for production (npm run build). The Minify module was doing that.

So the solution was to cancel this removal, setting the removeAttributeQuotes attribute to false:

minify: {
    ...
    removeAttributeQuotes: false,
    ...
}

In my development environment, I set it on the "webpack.prod.conf.js" file. Set it at your equivalent file.

Just rebuild and it's now working.

Determine if two rectangles overlap each other?

struct rect
{
    int x;
    int y;
    int width;
    int height;
};

bool valueInRange(int value, int min, int max)
{ return (value >= min) && (value <= max); }

bool rectOverlap(rect A, rect B)
{
    bool xOverlap = valueInRange(A.x, B.x, B.x + B.width) ||
                    valueInRange(B.x, A.x, A.x + A.width);

    bool yOverlap = valueInRange(A.y, B.y, B.y + B.height) ||
                    valueInRange(B.y, A.y, A.y + A.height);

    return xOverlap && yOverlap;
}

Get commit list between tags in git

git log takes a range of commits as an argument:

git log --pretty=[your_choice] tag1..tag2

See the man page for git rev-parse for more info.

Plotting multiple time series on the same plot using ggplot()

If both data frames have the same column names then you should add one data frame inside ggplot() call and also name x and y values inside aes() of ggplot() call. Then add first geom_line() for the first line and add second geom_line() call with data=df2 (where df2 is your second data frame). If you need to have lines in different colors then add color= and name for eahc line inside aes() of each geom_line().

df1<-data.frame(x=1:10,y=rnorm(10))
df2<-data.frame(x=1:10,y=rnorm(10))

ggplot(df1,aes(x,y))+geom_line(aes(color="First line"))+
  geom_line(data=df2,aes(color="Second line"))+
  labs(color="Legend text")

enter image description here

How to see the actual Oracle SQL statement that is being executed

Sorry for the short answer but it is late. Google "oracle event 10046 sql trace". It would be best to trace an individual session because figuring which SQL belongs to which session from v$sql is no easy if it is shared sql and being used by multiple users.

If you want to impress your Oracle DBA friends, learn how to set an oracle trace with event 10046, interpret the meaning of the wait events and find the top cpu consumers.

Quest had a free product that allowed you to capture the SQL as it went out from the client side but not sure if it works with your product/version of Oracle. Google "quest oracle sql monitor" for this.

Good night.

MS SQL 2008 - get all table names and their row counts in a DB

Try this it's simple and fast

SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT] 
FROM   sys.tables AS T 
   INNER JOIN sys.sysindexes AS I ON T.object_id = I.id 
   AND I.indid < 2 ORDER  BY I.rows DESC

How to make canvas responsive

this seems to be working :

#canvas{
  border: solid 1px blue; 
  width:100%;
}

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

How to check if element exists using a lambda expression?

Try to use anyMatch of Lambda Expression. It is much better approach.

 boolean idExists = tabPane.getTabs().stream()
            .anyMatch(t -> t.getId().equals(idToCheck));

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

You could use the JS confirm function.

<form onSubmit="if(!confirm('Is the form filled out correctly?')){return false;}">
  <input type="submit" />
</form>

http://jsfiddle.net/jasongennaro/DBHEz/

Creating a 3D sphere in Opengl using Visual C++

It doesn't seem like anyone so far has addressed the actual problem with your original code, so I thought I would do that even though the question is quite old at this point.

The problem originally had to do with the projection in relation to the radius and position of the sphere. I think you'll find that the problem isn't too complicated. The program actually works correctly, it's just that what is being drawn is very hard to see.

First, an orthogonal projection was created using the call

gluOrtho2D(0.0, 499.0, 0.0, 499.0);

which "is equivalent to calling glOrtho with near = -1 and far = 1." This means that the viewing frustum has a depth of 2. So a sphere with a radius of anything greater than 1 (diameter = 2) will not fit entirely within the viewing frustum.

Then the calls

glLoadIdentity();
glutSolidSphere(5.0, 20.0, 20.0);

are used, which loads the identity matrix of the model-view matrix and then "[r]enders a sphere centered at the modeling coordinates origin of the specified radius." Meaning, the sphere is rendered at the origin, (x, y, z) = (0, 0, 0), and with a radius of 5.

Now, the issue is three-fold:

  1. Since the window is 500x500 pixels and the width and height of the viewing frustum is almost 500 (499.0), the small radius of the sphere (5.0) makes its projected area only slightly over one fiftieth (2*5/499) of the size of the window in each dimension. This means that the apparent size of the sphere would be roughly 1/2,500th (actually pi*5^2/499^2, which is closer to about 1/3170th) of the entire window, so it might be difficult to see. This is assuming the entire circle is drawn within the area of the window. It is not, however, as we will see in point 2.
  2. Since the viewing frustum has it's left plane at x = 0 and bottom plane at y = 0, the sphere will be rendered with its geometric center in the very bottom left corner of the window so that only one quadrant of the projected sphere will be visible! This means that what would be seen is even smaller, about 1/10,000th (actually pi*5^2/(4*499^2), which is closer to 1/12,682nd) of the window size. This would make it even more difficult to see. Especially since the sphere is rendered so close to the edges/corner of the screen where you might not think to look.
  3. Since the depth of the viewing frustum is significantly smaller than the diameter of the sphere (less than half), only a sliver of the sphere will be within the viewing frustum, rendering only that part. So you will get more like a hollow circle on the screen than a solid sphere/circle. As it happens, the thickness of that sliver might represent less than 1 pixel on the screen which means we might even see nothing on the screen, even if part of the sphere is indeed within the viewing frustum.

The solution is simply to change the viewing frustum and radius of the sphere. For instance,

gluOrtho2D(-5.0, 5.0, -5.0, 5.0);
glutSolidSphere(5.0, 20, 20);

renders the following image.

r = 5.0

As you can see, only a small part is visible around the "equator", of the sphere with a radius of 5. (I changed the projection to fill the window with the sphere.) Another example,

gluOrtho2D(-1.1, 1.1, -1.1, 1.1);
glutSolidSphere(1.1, 20, 20);

renders the following image.

r = 1.1

The image above shows more of the sphere inside of the viewing frustum, but still the sphere is 0.2 depth units larger than the viewing frustum. As you can see, the "ice caps" of the sphere are missing, both the north and the south. So, if we want the entire sphere to fit within the viewing frustum which has depth 2, we must make the radius less than or equal to 1.

gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
glutSolidSphere(1.0, 20, 20);

renders the following image.

r = 1.0

I hope this has helped someone. Take care!

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

How to multiply duration by integer?

In Go, you can multiply variables of same type, so you need to have both parts of the expression the same type.

The simplest thing you can do is casting an integer to duration before multiplying, but that would violate unit semantics. What would be multiplication of duration by duration in term of units?

I'd rather convert time.Millisecond to an int64, and then multiply it by the number of milliseconds, then cast to time.Duration:

time.Duration(int64(time.Millisecond) * int64(rand.Int31n(1000)))

This way any part of the expression can be said to have a meaningful value according to its type. int64(time.Millisecond) part is just a dimensionless value - the number of smallest units of time in the original value.

If walk a slightly simpler path:

time.Duration(rand.Int31n(1000)) * time.Millisecond

The left part of multiplication is nonsense - a value of type "time.Duration", holding something irrelevant to its type:

numberOfMilliseconds := 100
// just can't come up with a name for following:
someLHS := time.Duration(numberOfMilliseconds)
fmt.Println(someLHS)
fmt.Println(someLHS*time.Millisecond)

And it's not just semantics, there is actual functionality associated with types. This code prints:

100ns
100ms

Interestingly, the code sample here uses the simplest code, with the same misleading semantics of Duration conversion: https://golang.org/pkg/time/#Duration

seconds := 10

fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

Writing binary number system in C code

Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b prefix:

int foo = 0b1010;

If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:

#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
        unsigned long long i = 0;
        while (*s) {
                i <<= 1;
                i += *s++ - '0';
        }
        return i;
}

And then you can use it like this:

int foo = B(1010);

If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.

Proof:

The following code:

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


#define B(x) S_to_binary_(#x)

static inline unsigned long long S_to_binary_(const char *s)
{
    unsigned long long i = 0;
    while (*s) {
        i <<= 1;
        i += *s++ - '0';
    }
    return i;
}

int main()
{
    int foo = B(001100101);

    printf("%d\n", foo);

    return 0;
}

has been compiled using clang -o baz.S baz.c -Wall -O3 -S, and it produced the following assembly:

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    leaq    L_.str1(%rip), %rdi
    movl    $101, %esi               ## <= This line!
    xorb    %al, %al
    callq   _printf
    xorl    %eax, %eax
    popq    %rbp
    ret
    .cfi_endproc

    .section    __TEXT,__cstring,cstring_literals
L_.str1:                                ## @.str1
    .asciz   "%d\n"


.subsections_via_symbols

So clang completely eliminated the call to the function, and replaced its return value with 101. Neat, huh?

Connect Bluestacks to Android Studio

world !

No need to do execute batch command. With the current version, just run BLUESTACKS before ANDROID STUDIO

convert month from name to number

$monthname = date("F", strtotime($month));

F means full month name

Position a div container on the right side

Just wanna update this for beginners now you should definitly use flexbox to do that, it's more appropriate and work for responsive try this : http://jsfiddle.net/x5vyC/3957/

#wrapper{
  display:flex;
  justify-content:space-between;
  background:red;
}


#c1{
   background:blue;
}


#c2{
    background:green;
}

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

How to push a single file in a subdirectory to Github (not master)

When you do a push, git only takes the changes that you have committed.

Remember when you do a git status it shows you the files you changed since the last push?

Once you commit those changes and do a push they are the only files that get pushed so you don't have to worry about thinking that the entire master gets pushed because in reality it does not.

How to push a single file:

git commit yourfile.js
git status
git push origin master

How to change font size in Eclipse for Java text editors?

Press ctrl + - to decrease, and ctrl + + to increase the Font Size.

It's working for me in Eclipse Oxygen.

Java, Simplified check if int array contains int

Try this:

public static void arrayContains(){
    int myArray[]={2,2,5,4,8};

    int length=myArray.length;

    int toFind = 5;
    boolean found = false;

    for(int i = 0; i < length; i++) {
        if(myArray[i]==toFind) {
            found=true;
        }
    }

    System.out.println(myArray.length);
    System.out.println(found); 
}

How do I make a fully statically linked .exe with Visual Studio Express 2005?

For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.

If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.

How get data from material-ui TextField, DropDownMenu components?

Here's the simplest solution i came up with, we get the value of the input created by material-ui textField :

      create(e) {
        e.preventDefault();
        let name = this.refs.name.input.value;
        alert(name);
      }

      constructor(){
        super();
        this.create = this.create.bind(this);
      }

      render() {
        return (
              <form>
                <TextField ref="name" hintText="" floatingLabelText="Your name" /><br/>
                <RaisedButton label="Create" onClick={this.create} primary={true} />
              </form>
        )}

hope this helps.

Force an Android activity to always use landscape mode

A quick and simple solution is for the AndroidManifest.xml file, add the following for each activity that you wish to force to landscape mode:

android:screenOrientation="landscape"

printf() formatting for hex

The %#08X conversion must precede the value with 0X; that is required by the standard. There's no evidence in the standard that the # should alter the behaviour of the 08 part of the specification except that the 0X prefix is counted as part of the length (so you might want/need to use %#010X. If, like me, you like your hex presented as 0x1234CDEF, then you have to use 0x%08X to achieve the desired result. You could use %#.8X and that should also insert the leading zeroes.

Try variations on the following code:

#include <stdio.h>

int main(void)
{
    int j = 0;
    printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    for (int i = 0; i < 8; i++)
    {
        j = (j << 4) | (i + 6);
        printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    }
    return(0);
}

On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:

0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd

I'm a little surprised at the treatment of 0; I'm not clear why the 0X prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the # option.


The treatment of zero is according to the standard.

ISO/IEC 9899:2011 §7.21.6.1 The fprintf function

¶6 The flag characters and their meanings are:
...
# The result is converted to an "alternative form". ... For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. ...

(Emphasis added.)


Note that using %#X will use upper-case letters for the hex digits and 0X as the prefix; using %#x will use lower-case letters for the hex digits and 0x as the prefix. If you prefer 0x as the prefix and upper-case letters, you have to code the 0x separately: 0x%X. Other format modifiers can be added as needed, of course.

For printing addresses, use the <inttypes.h> header and the uintptr_t type and the PRIXPTR format macro:

#include <inttypes.h>
#include <stdio.h>

int main(void)
{
    void *address = &address;  // &address has type void ** but it converts to void *
    printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
    return 0;
}

Example output:

Address 0x7FFEE5B29428

Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the . to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).

Event listener for when element becomes visible?

There is at least one way, but it's not a very good one. You could just poll the element for changes like this:

var previous_style,
    poll = window.setInterval(function()
{
    var current_style = document.getElementById('target').style.display;
    if (previous_style != current_style) {
        alert('style changed');
        window.clearInterval(poll);
    } else {
        previous_style = current_style;
    }
}, 100);

The DOM standard also specifies mutation events, but I've never had the chance to use them, and I'm not sure how well they're supported. You'd use them like this:

target.addEventListener('DOMAttrModified', function()
{
    if (e.attrName == 'style') {
        alert('style changed');
    }
}, false);

This code is off the top of my head, so I'm not sure if it'd work.

The best and easiest solution would be to have a callback in the function displaying your target.

How to format date in angularjs

var app=angular.module('myApp',[]);
        app.controller('myController',function($scope){         
              $scope.names = ['1288323623006','1388323623006'];

        });

Here Controller name is "myController" and app name is "myApp".

<div ng-app="myApp" ng-controller="myController">
        <ul>
            <li ng-repeat="x in names">
                {{x | date:'mm-dd-yyyy'}}

            </li>

        </ul>
    </div>

Result will look like this :- * 10-29-2010 * 01-03-2013

Count the number occurrences of a character in a string

Regular expressions maybe?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))

TypeError: Image data can not convert to float

From what I understand of the scikit-image docs (http://scikit-image.org/docs/dev/index.html), imshow() takes a ndarray as an argument, and not a dictionary:

http://scikit-image.org/docs/dev/api/skimage.io.html?highlight=imshow#skimage.io.imshow

Maybe if you post the whole stack trace, we could see that the TypeError comes somewhere deep from imshow().