Programs & Examples On #Wubi

CMD: Export all the screen content to a text file

How about this:

<command> > <filename.txt> & <filename.txt>

Example:

ipconfig /all > network.txt & network.txt

This will give the results in Notepad instead of the command prompt.

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

How to include CSS file in Symfony 2 and Twig?

In case you are using Silex add the Symfony Asset as a dependency:

composer require symfony/asset

Then you may register Asset Service Provider:

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.version_format' => '%s?version=%s',
    'assets.named_packages' => array(
        'css' => array(
            'version' => 'css2',
            'base_path' => __DIR__.'/../public_html/resources/css'
        ),
        'images' => array(
            'base_urls' => array(
                'https://img.example.com'
            )
        ),
    ),
));

Then in your Twig template file in head section:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {% block head %}
    <link rel="stylesheet" href="{{ asset('style.css') }}" />
    {% endblock %}
</head>
<body>

</body>
</html>

How do you exit from a void function in C++?

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])

CSV parsing in Java - working example..?

At a minimum you are going to need to know the column delimiter.

How to find the path of Flutter SDK

To find the Flutter SDK path [ used Windows10 ]

  1. In your Android Studio home page on the bottom right click on Configure
  2. Then Click on SDK Manager
  3. Then on System Settings
  4. Then on AndroidSDK

You will see the path at the top

PHP, getting variable from another php-file

You could also use file_get_contents

 $url_a="http://127.0.0.1/get_value.php?line=a&shift=1&tgl=2017-01-01";
 $data_a=file_get_contents($url_a);

 echo $data_a;

Bootstrap Modal Backdrop Remaining

The problem is that bootstrap removes the backdrop asynchronously. So when you call hide and show quickly after each other, the backdrop isn't removed.

The solution (as you've mentioned) is to wait for the modal to have been hidden completely, using the 'hidden.bs.modal' event. Use jQuery one to only perform the callback once. I've forked your jsfiddle to show how this would work.

// wait for the backdrop to be removed nicely.
loadingModal.one('hidden.bs.modal', function()
{
    loadingModal.modal("show");

    //Again simulate 3 seconds
    setTimeout(function () {
        loadingModal.modal("hide");
    }, 3000);
});
// hide for the first time, after binding to the hidden event.
loadingModal.modal("hide");

Looking through the code in Bootstrap:

This is what makes hiding the modal asynchronous:

$.support.transition && this.$element.hasClass('fade') ?
    this.$element
        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
        .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
    this.hideModal()

This checks whether transitions are supported and the fade class is included on the modal. When both are true, it waits for the fade effect to complete, before hiding the modal. This waiting happens again before removing the backdrop.

This is why removing the fade class will make hiding the modal synchronous (no more waiting for CSS fade effect to complete) and why the solution by reznic works.

This check determines whether to add or remove the backdrop. isShown = true is performed synchronously. When you call hide and show quickly after each other, isShown becomes true and the check adds a backdrop, instead of removing the previous one, creating the problem you're having.

How to clear the entire array?

For deleting a dynamic array in VBA use the instruction Erase.

Example:

Dim ArrayDin() As Integer    
ReDim ArrayDin(10)    'Dynamic allocation 
Erase ArrayDin        'Erasing the Array   

Hope this help!

Text size of android design TabLayout tabs

Do as following.

1. Add the Style to the XML

    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
    </style>

2. Apply Style

Find the Layout containing the TabLayout and add the style. The added line is bold.

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/MyTabLayoutTextAppearance" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Compare two files line by line and generate the difference in another file

Sometimes diff is the utility you need, but sometimes join is more appropriate. The files need to be pre-sorted or, if you are using a shell which supports process substitution such as bash, ksh or zsh, you can do the sort on the fly.

join -v 1 <(sort file1) <(sort file2)

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

How to store a byte array in Javascript

I wanted a more exact and useful answer to this question. Here's the real answer (adjust accordingly if you want a byte array specifically; obviously the math will be off by a factor of 8 bits : 1 byte):

class BitArray {
  constructor(bits = 0) {
    this.uints = new Uint32Array(~~(bits / 32));
  }

  getBit(bit) {
    return (this.uints[~~(bit / 32)] & (1 << (bit % 32))) != 0 ? 1 : 0;
  }

  assignBit(bit, value) {
    if (value) {
      this.uints[~~(bit / 32)] |= (1 << (bit % 32));
    } else {
      this.uints[~~(bit / 32)] &= ~(1 << (bit % 32));
    }
  }

  get size() {
    return this.uints.length * 32;
  }

  static bitsToUints(bits) {
    return ~~(bits / 32);
  }
}

Usage:

let bits = new BitArray(500);
for (let uint = 0; uint < bits.uints.length; ++uint) {
  bits.uints[uint] = 457345834;
}
for (let bit = 0; bit < 50; ++bit) {
  bits.assignBit(bit, 1);
}
str = '';
for (let bit = bits.size - 1; bit >= 0; --bit) {
  str += bits.getBit(bit);
}
str;

Output:

"00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000101000101100101010
 00011011010000111111111111111111
 11111111111111111111111111111111"

Note: This class is really slow to e.g. assign bits (i.e. ~2s per 10 million assignments) if it's created as a global variable, at least in the Firefox 76.0 Console on Linux... If, on the other hand, it's created as a variable (i.e. let bits = new BitArray(1e7);), then it's blazingly fast (i.e. ~300ms per 10 million assignments)!


For more info, see here:

Note that I used Uint32Array because there's no way to directly have a bit/byte array (that you can interact with directly) and because even though there's a BigUint64Array, JS only supports 32 bits:

Bitwise operators treat their operands as a sequence of 32 bits

...

The operands of all bitwise operators are converted to...32-bit integers

implement time delay in c

// Provides ANSI C method of delaying x milliseconds

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

void delayMillis(unsigned long ms) {
    clock_t start_ticks = clock();
    unsigned long millis_ticks = CLOCKS_PER_SEC/1000;
    while (clock()-start_ticks < ms*millis_ticks) {
    }
}    

/* 
 * Example output:
 * 
 * CLOCKS_PER_SEC:[1000000]
 * 
 * Test Delay of 800 ms....
 * 
 * start[2054], end[802058], 
 * elapsedSec:[0.802058]
 */
int testDelayMillis() {

    printf("CLOCKS_PER_SEC:[%lu]\n\n", CLOCKS_PER_SEC);
    clock_t start_t, end_t;
    start_t = clock();
    printf("Test Delay of 800 ms....\n", CLOCKS_PER_SEC);
    delayMillis(800); 
    end_t = clock();
    double elapsedSec = end_t/(double)CLOCKS_PER_SEC;
    printf("\nstart[%lu], end[%lu], \nelapsedSec:[%f]\n", start_t, end_t, elapsedSec);

}

int main() {    
    testDelayMillis();
}

StringBuilder vs String concatenation in toString() in Java

The key is whether you are writing a single concatenation all in one place or accumulating it over time.

For the example you gave, there's no point in explicitly using StringBuilder. (Look at the compiled code for your first case.)

But if you are building a string e.g. inside a loop, use StringBuilder.

To clarify, assuming that hugeArray contains thousands of strings, code like this:

...
String result = "";
for (String s : hugeArray) {
    result = result + s;
}

is very time- and memory-wasteful compared with:

...
StringBuilder sb = new StringBuilder();
for (String s : hugeArray) {
    sb.append(s);
}
String result = sb.toString();

Android Facebook style slide

As a part of my Android Common Library (ACL) I implemented own SideBar. Main advantages:

  1. Side bar can be set to any position: left, top, bottom, right
  2. Both main view and sliding view are clickable
  3. Side bar can be partially shown
  4. Stylable attributes for SideBar make easier to change it's style
  5. Artifact in maven repo
  6. Part of a big library

Source code: https://github.com/serso/android-common/tree/master/views/src/main/java/org/solovyev/android/view/sidebar

Usage: https://github.com/serso/android-common/blob/master/samples/res/layout/acl_view_layout.xml

What is the right way to populate a DropDownList from a database?

((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;

What is the difference between canonical name, simple name and class name in Java Class?

this is best document I found describing getName(), getSimpleName(), getCanonicalName()

https://javahowtodoit.wordpress.com/2014/09/09/java-lang-class-what-is-the-difference-between-class-getname-class-getcanonicalname-and-class-getsimplename/

// Primitive type
int.class.getName();          // -> int
int.class.getCanonicalName(); // -> int
int.class.getSimpleName();    // -> int

// Standard class
Integer.class.getName();          // -> java.lang.Integer
Integer.class.getCanonicalName(); // -> java.lang.Integer
Integer.class.getSimpleName();    // -> Integer

// Inner class
Map.Entry.class.getName();          // -> java.util.Map$Entry
Map.Entry.class.getCanonicalName(); // -> java.util.Map.Entry
Map.Entry.class.getSimpleName();    // -> Entry     

// Anonymous inner class
Class<?> anonymousInnerClass = new Cloneable() {}.getClass();
anonymousInnerClass.getName();          // -> somepackage.SomeClass$1
anonymousInnerClass.getCanonicalName(); // -> null
anonymousInnerClass.getSimpleName();    // -> // An empty string

// Array of primitives
Class<?> primitiveArrayClass = new int[0].getClass();
primitiveArrayClass.getName();          // -> [I
primitiveArrayClass.getCanonicalName(); // -> int[]
primitiveArrayClass.getSimpleName();    // -> int[]

// Array of objects
Class<?> objectArrayClass = new Integer[0].getClass();
objectArrayClass.getName();          // -> [Ljava.lang.Integer;
objectArrayClass.getCanonicalName(); // -> java.lang.Integer[]
objectArrayClass.getSimpleName();    // -> Integer[]

Response.Redirect to new window

Here's a jQuery version based on the answer by @takrl and @tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic:

<asp:Button ID="btnSubmit" OnClientClick="openNewWin();"  Text="Submit" OnClick="btn_OnClick" runat="server"/>

Then in your js file referenced on the SAME page:

function openNewWin () {
    $('form').attr('target','_blank');
    setTimeout('resetFormTarget()', 500);
}

function resetFormTarget(){
    $('form').attr('target','');
}

How to specify jdk path in eclipse.ini on windows 8 when path contains space

tl;dr

The -vm option must occur after the other Eclipse-specific options (such as -product, --launcher.*, etc), but before the -vmargs option, since everything after -vmargs is passed directly to the JVM. Add the -vm option on its own line and the path to your JDK executable on the following line; e.g.

-vm
C:\Program Files\Java\jdk1.8.0_161\bin\javaw.exe

Details

Notes

  • The path is on a new line below the -vm option
  • There is no need to escape any characters or use slashes (back-slashes are fine)
  • The path points to the bin directory, not to javaw.exe

Gotcha JAVA_HOME

When you don't specify a virtual machine in your eclipse.ini file, you may think that the JAVA_HOME environment variable is used, but this is not the case!
From FAQ_How_do_I_run_Eclipse#Find_the_JVM

Eclipse DOES NOT consult the JAVA_HOME environment variable.

Instead the Windows search path will be scanned.

Recommendation
You may think it is a good idea to use the search path, because it is flexible.
While this is true, it also has the downside that the search path may be altered by installing or updating programs.
Thus, I recommend to use the explicit setting in the eclipse.ini file.

Finding a VM

The reason why you should specify the bin directory and not the javaw.exe (as proposed by many other answers), is that the launcher can then dynamically choose which is the best way to start the JVM. See details of the launcher process for all details:

We look in that directory for: (1) a default.ee file, (2) a java launcher or (3) the jvm shared library.

Verfication

You can verify which VM is used by your running eclipse instance in the Configuration dialogue.
In eclipse Oxygen go to Help - About Eclipse - Installation Details - Configuration

You will see which VM path eclipse has chosen, e.g.:

eclipse.vm=C:\Program Files\Java\jdk1.8.0_161\bin\..\jre\bin\server\jvm.dll

Clearing content of text file using php

Use 'w' and not, 'a'.

if (!$handle = fopen($file, 'w'))

Why doesn't CSS ellipsis work in table cell?

It's also important to put

table-layout:fixed;

Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

Android: alternate layout xml for landscape mode

By default, the layouts in /res/layout are applied to both portrait and landscape.

If you have for example

/res/layout/main.xml

you can add a new folder /res/layout-land, copy main.xml into it and make the needed adjustments.

orientation

See also http://www.androidpeople.com/android-portrait-amp-landscape-differeent-layouts and http://www.devx.com/wireless/Article/40792/1954 for some more options.

Parsing JSON Object in Java

public class JsonParsing {

public static Properties properties = null;

public static JSONObject jsonObject = null;

static {
    properties = new Properties();
}

public static void main(String[] args) {

    try {

        JSONParser jsonParser = new JSONParser();

        File file = new File("src/main/java/read.json");

        Object object = jsonParser.parse(new FileReader(file));

        jsonObject = (JSONObject) object;

        parseJson(jsonObject);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static void getArray(Object object2) throws ParseException {

    JSONArray jsonArr = (JSONArray) object2;

    for (int k = 0; k < jsonArr.size(); k++) {

        if (jsonArr.get(k) instanceof JSONObject) {
            parseJson((JSONObject) jsonArr.get(k));
        } else {
            System.out.println(jsonArr.get(k));
        }

    }
}

public static void parseJson(JSONObject jsonObject) throws ParseException {

    Set<Object> set = jsonObject.keySet();
    Iterator<Object> iterator = set.iterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        if (jsonObject.get(obj) instanceof JSONArray) {
            System.out.println(obj.toString());
            getArray(jsonObject.get(obj));
        } else {
            if (jsonObject.get(obj) instanceof JSONObject) {
                parseJson((JSONObject) jsonObject.get(obj));
            } else {
                System.out.println(obj.toString() + "\t"
                        + jsonObject.get(obj));
            }
        }
    }
}}

How to include PHP files that require an absolute path?

This should work

$root = realpath($_SERVER["DOCUMENT_ROOT"]);

include "$root/inc/include1.php";

Edit: added imporvement by aussieviking

Is there a simple, elegant way to define singletons?

The Singleton Pattern implemented with Python courtesy of ActiveState.

It looks like the trick is to put the class that's supposed to only have one instance inside of another class.

How to get a value from a Pandas DataFrame and not the index and object type

Nobody mentioned it, but you can also simply use loc with the index and column labels.

df.loc[2, 'Letters']
# 'C'

Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.

df.set_index('Numbers').loc[3, 'Letters']

How to hide element using Twitter Bootstrap and show it using jQuery?

Recently ran into this when upgrading from 2.3 to 3.1; our jQuery animations (slideDown) broke because we were putting hide on the elements in the page template. We went the route of creating name-spaced versions of Bootstrap classes that now carry the ugly !important rule.

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

box-shadow on bootstrap 3 container

Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.

Example: http://jsfiddle.net/SHLu4/2/

It'll be something like:

<div class="container drop-shadow">
    <div class="container">
        <div class="row">
            <div class="col-md-8">Main Area</div>
            <div class="col-md-4">Side Area</div>
        </div>
    </div>
</div>

And your CSS:

<style>
    .drop-shadow {
        -webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
        box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
    }
    .container.drop-shadow {
        padding-left:0;
        padding-right:0;
    }
</style>

Where to change default pdf page width and font size in jspdf.debug.js?

Besides using one of the default formats you can specify any size you want in the unit you specify.

For example:

// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);

The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).

Your 1st parameter (landscape or portrait) determines what becomes the width and the height.

In the sourcecode on GitHub you can see the supported units (relative proportions to pt), and you can also see the default page formats (with their sizes in pt).

Using Switch Statement to Handle Button Clicks

One way of achieving this is to make your class implement OnClickListener and then add it to your buttons like this:

Example:

//make your class implement OnClickListener
public class MyClass implements OnClickListener{

        ...

        //Create your buttons and set their onClickListener to "this"
        Button b1 = (Button) findViewById(R.id.buttonplay);   
        b1.setOnClickListener(this);

        Button b2 = (Button) findViewById(R.id.buttonstop);   
        b2.setOnClickListener(this);

        ...

        //implement the onClick method here
        public void onClick(View v) {
           // Perform action on click
          switch(v.getId()) {
            case R.id.buttonplay:
              //Play voicefile
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
              break;
            case R.id.buttonstop:
              //Stop MediaPlayer
              MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
              break;
          }
       }
}

For more information see Android Developers > Handling UI Events.

Execute Shell Script after post build in Jenkins

You'd have to set up the post-build shell script as a separate Jenkins job and trigger it as a post-build step. It looks like you will need to use the Parameterized Trigger Plugin as the standard "Build other projects" option only works if your triggering build is successful.

NTFS performance and large volumes of files and directories

I had real experience with about 100 000 files (each several MBs) on NTFS in a directory while copying one online library.

It takes about 15 minutes to open the directory with Explorer or 7-zip.

Writing site copy with winhttrack will always get stuck after some time. It dealt also with directory, containing about 1 000 000 files. I think the worst thing is that the MFT can only by traversed sequentially.

Opening the same under ext2fsd on ext3 gave almost the same timing. Probably moving to reiserfs (not reiser4fs) can help.

Trying to avoid this situation is probably the best.

For your own programs using blobs w/o any fs could be beneficial. That's the way Facebook does for storing photos.

Split Div Into 2 Columns Using CSS

When you float those two divs, the content div collapses to zero height. Just add

<br style="clear:both;"/>

after the #right div but inside the content div. That will force the content div to surround the two internal, floating divs.

How to make python Requests work via socks proxy

As soon as python requests will be merged with SOCKS5 pull request it will do as simple as using proxies dictionary:

#proxy
        # SOCKS5 proxy for HTTP/HTTPS
        proxies = {
            'http' : "socks5://myproxy:9191",
            'https' : "socks5://myproxy:9191"
        }

        #headers
        headers = {

        }

        url='http://icanhazip.com/'
        res = requests.get(url, headers=headers, proxies=proxies)

See SOCKS Proxy Support

Another options, in case that you cannot wait request to be ready, when you cannot use requesocks - like on GoogleAppEngine due to the lack of pwd built-in module, is to use PySocks that was mentioned above:

  1. Grab the socks.py file from the repo and put a copy in your root folder;
  2. Add import socks and import socket

At this point configure and bind the socket before using with urllib2 - in the following example:

import urllib2
import socket
import socks

socks.set_default_proxy(socks.SOCKS5, "myprivateproxy.net",port=9050)
socket.socket = socks.socksocket
res=urllib2.urlopen(url).read()

How do I set GIT_SSL_NO_VERIFY for specific repos only?

This question keeps coming up and I did not find a satisfying result yet, so here is what worked for me (based on a previous answer https://stackoverflow.com/a/52706362/1806760, which is not working):

My server is https://gitlab.dev with a self-signed certificate.

First run git config --system --edit (from an elevated command prompt, change --system to --global if you want to do it for just your user), then insert the following snippet after any previous [http] sections:

[http "https://gitlab.dev"]
        sslVerify = false

Then check if you did everything correctly:

> git config --type=bool --get-urlmatch http.sslVerify https://gitlab.dev
false

iterating over each character of a String in ruby 1.8.6 (each_char)

Extending la_f0ka's comment, esp. if you also need the index position in your code, you should be able to do

s = 'ABCDEFG'
for pos in 0...s.length
    puts s[pos].chr
end

The .chr is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.

How to modify existing, unpushed commit messages?

As already mentioned, git commit --amend is the way to overwrite the last commit. One note: if you would like to also overwrite the files, the command would be

git commit -a --amend -m "My new commit message"

Binding an enum to a WinForms combo box, and then setting it

The Enum

public enum Status { Active = 0, Canceled = 3 }; 

Setting the drop down values from it

cbStatus.DataSource = Enum.GetValues(typeof(Status));

Getting the enum from the selected item

Status status; 
Enum.TryParse<Status>(cbStatus.SelectedValue.ToString(), out status); 

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

Drawing a line/path on Google Maps

Thank you for your help. At last I could draw a line on the map. This is how I done it:

/** Called when the activity is first created. */
private List<Overlay> mapOverlays;

private Projection projection;  

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

    linearLayout = (LinearLayout) findViewById(R.id.zoomview);
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);

    mapOverlays = mapView.getOverlays();        
    projection = mapView.getProjection();
    mapOverlays.add(new MyOverlay());        

}

@Override
protected boolean isRouteDisplayed() {
    return false;
}

class MyOverlay extends Overlay{

    public MyOverlay(){

    }   

    public void draw(Canvas canvas, MapView mapv, boolean shadow){
        super.draw(canvas, mapv, shadow);

        Paint   mPaint = new Paint();
        mPaint.setDither(true);
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(2);

        GeoPoint gP1 = new GeoPoint(19240000,-99120000);
        GeoPoint gP2 = new GeoPoint(37423157, -122085008);

        Point p1 = new Point();
        Point p2 = new Point();
        Path path = new Path();

        Projection projection=mapv.getProjection();
        projection.toPixels(gP1, p1);
        projection.toPixels(gP2, p2);

        path.moveTo(p2.x, p2.y);
        path.lineTo(p1.x,p1.y);

        canvas.drawPath(path, mPaint);
    }

Reading values from DataTable

I think it will work

for (int i = 1; i <= broj_ds; i++ ) 
  { 

     QuantityInIssueUnit_value = dr_art_line_2[i]["Column"];
     QuantityInIssueUnit_uom  = dr_art_line_2[i]["Column"];

  }

Change link color of the current page with CSS

It is possible to achieve this without having to modify each page individually (adding a 'current' class to a specific link), but still without JS or a server-side script. This uses the :target pseudo selector, which relies on #someid appearing in the addressbar.

<!DOCTYPE>
<html>
<head>
    <title>Some Title</title>
<style>
:target {
    background-color: yellow;
}
</style>
</head>
<body>
<ul>
    <li><a id="news" href="news.html#news">News</a></li>
    <li><a id="games" href="games.html#games">Games</a></li>
    <li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>

There are a couple of restrictions:

  • If the page wasn't navigated to using one of these links it won't be coloured;
  • The ids need to occur at the top of the page otherwise the page will jump down a bit when visited.

As long as any links to these pages include the id, and the navbar is at the top, it shouldn't be a problem.


Other in-page links (bookmarks) will also cause the colour to be lost.

Markdown and including multiple files

I think we better adopt a new file inclusion syntax (so won't mess up with code blocks, I think the C style inclusion is totally wrong), and I wrote a small tool in Perl, naming cat.pl, because it works like cat (cat a.txt b.txt c.txt will merge three files), but it merges files in depth, not in width. How to use?

$ perl cat.pl <your file>

The syntax in detail is:

  • recursive include files: @include <-=path=
  • just include one: %include <-=path=

It can properly handle file inclusion loops (if a.txt <- b.txt, b.txt <- a.txt, then what you expect?).

Example:

a.txt:

a.txt

    a <- b

    @include <-=b.txt=

a.end

b.txt:

b.txt

    b <- a

    @include <-=a.txt=

b.end

perl cat.pl a.txt > c.txt, c.txt:

a.txt

    a <- b

    b.txt

        b <- a

        a.txt

            a <- b

            @include <-=b.txt= (note:won't include, because it will lead to infinite loop.)

        a.end

    b.end

a.end

More examples at https://github.com/district10/cat/blob/master/tutorial_cat.pl_.md.

I also wrote a Java version having an identical effect (not the same, but close).

How can I simulate an anchor click via jquery?

JQuery('#left').triggerHandler('click'); works fine in Firefox and IE7. I haven't tested it on other browsers.

If want to trigger automatic user clicks do the following:

window.setInterval(function() 
    {
        $('#left').triggerHandler('click');
    }, 1000);

How to convert a String to Bytearray

The easiest way in 2018 should be TextEncoder but the returned element is not byte array, it is Uint8Array. (And not all browsers support it)

let utf8Encode = new TextEncoder();
utf8Encode.encode("eee")
> Uint8Array [ 101, 101, 101 ]

Angular ng-repeat add bootstrap row every 3 or 4 cols

After combining many answers and suggestion here, this is my final answer, which works well with flex, which allows us to make columns with equal height, it also checks the last index, and you don't need to repeat the inner HTML. It doesn't use clearfix:

<div ng-repeat="prod in productsFiltered=(products | filter:myInputFilter)" ng-if="$index % 3 == 0" class="row row-eq-height">
    <div ng-repeat="i in [0, 1, 2]" ng-init="product = productsFiltered[$parent.$parent.$index + i]"  ng-if="$parent.$index + i < productsFiltered.length" class="col-xs-4">
        <div class="col-xs-12">{{ product.name }}</div>
    </div>
</div>

It will output something like this:

<div class="row row-eq-height">
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
</div>
<div class="row row-eq-height">
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
</div>

Get day of week using NSDate

For Swift4 to get weekday from string

   func getDayOfWeek(today:String)->Int {
        let formatter  = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let todayDate = formatter.date(from: today)!
        let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
        let myComponents = myCalendar.components(NSCalendar.Unit.weekday, from: todayDate)
        let weekDay = myComponents.weekday
        return weekDay!
    }

let weekday = getDayOfWeek(today: "2018-10-10")
print(weekday) // 4

Correct way to handle conditional styling in React

instead of this:

style={{
  textDecoration: completed ? 'line-through' : 'none'
}}

you could try the following using short circuiting:

style={{
  textDecoration: completed && 'line-through'
}}

https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb

key bit of information from the link:

Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.

It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.

The other solutions might be more best practice, but thought it would be worth sharing.

npm install private github repositories by dependency in package.json

The accepted answer works, but I don't like much the idea to paste secure tokens into the package.json

I have found it elsewhere, just run this one-time command as documented in the git-config manpage.

git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf [email protected]:

GITHUB_TOKEN may be setup as environmnet variable or pasted directly

and then I install private github repos like: npm install user/repo --save


works also in Heroku, just setup the above git config ... command as heroku-prebuild script in package.json and setup GITHUB_TOKEN as Heroku config variable.

Refresh Fragment at reload

Make use of onResume method... both on the fragment activity and the activity holding the fragment.

Disabled form inputs do not appear in the request

Simple workaround - just use hidden field as placeholder for select, checkbox and radio.

From this code to -

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <!-- this does not appear in request -->
    <input type="textbox" name="Percentage" value="100" disabled="disabled" /> 
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>

</form>

that code -

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <input type="textbox" value="100" readonly /> 

    <input type="hidden" name="gender" value="female" />
    <select name="gender" disabled="disabled">
          <option value="male">Male</option>
          <option value="female" selected>Female</option>
    </select>
</form>

How to check if a string starts with a specified string?

There is also the strncmp() function and strncasecmp() function which is perfect for this situation:

if (strncmp($string_n, "http", 4) === 0)

In general:

if (strncmp($string_n, $prefix, strlen($prefix)) === 0)

The advantage over the substr() approach is that strncmp() just does what needs to be done, without creating a temporary string.

How to view UTF-8 Characters in VIM or Gvim

I couldn't get any other fonts I installed to show up in my Windows GVim editor, so I just switched to Lucida Console which has at least somewhat better UTF-8 support. Add this to the end of your _vimrc:

" For making everything utf-8
set enc=utf-8
set guifont=Lucida_Console:h9:cANSI
set guifontwide=Lucida_Console:h12

Now I see at least some UTF-8 characters.

Select rows having 2 columns equal value

select * from test;
a1  a2  a3
1   1   2
1   2   2
2   1   2

select t1.a3 from test t1, test t2 where t1.a1 = t2.a1 and t2.a2 = t1.a2 and t1.a1 = t2.a2

a3
1

You can try same thing using Joins too..

Xcode "Device Locked" When iPhone is unlocked

All the previous solutions didn't work.

Finlay, changing the iPhone's cable solved the problem.

How to Parse JSON Array with Gson

you can get List value without using Type object.

EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));

I have tested it and it is working.

Is there a way to get rid of accents and convert a whole string to regular letters?

System.out.println(Normalizer.normalize("àèé", Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""));

worked for me. The output of the snippet above gives "aee" which is what I wanted, but

System.out.println(Normalizer.normalize("àèé", Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""));

didn't do any substitution.

MySQL Multiple Joins in one query?

I shared my experience of using two LEFT JOINS in a single SQL query.

I have 3 tables:

Table 1) Patient consists columns PatientID, PatientName

Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID

Table 3) Doctor consists columns DoctorID, DoctorName


Query:

SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname

FROM Appointment 

LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId  //have doctorId column common

LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId      //have patientid column common

WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE

AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates 

ORDER BY AppointmentDateTime ASC;  // getting data as ascending order

I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")

Node.js quick file server (static files over HTTP)

A simple Static-Server using connect

var connect = require('connect'),
  directory = __dirname,
  port = 3000;

connect()
  .use(connect.logger('dev'))
  .use(connect.static(directory))
  .listen(port);

console.log('Listening on port ' + port);

See also Using node.js as a simple web server

Which version of MVC am I using?

Select the System.Web.Mvc assembly in the "References" folder in the solution explorer. Bring up the properties window (F4) and check the Version

Reference Properties

Error In PHP5 ..Unable to load dynamic library

Look /etc/php5/cli/conf.d/ and delete corresponding *.ini files. This error happens when you remove some php packages not so cleanly.

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

Saving lists to txt file

Framework 4: no need to use StreamWriter:

System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

i have experienced the same problem, and after reading this post i have double checked the JAVA_HOME definition in .bash_profile. It is actually:

export JAVA_HOME=$(which java)

that, exactly as Anony-Mousse is explaining, is the executable. Changing it to:

export=/Library/Java/Home

fixes the problem, tho is still interesting to understand why it's valued in that way in the profile file.

Could not autowire field in spring. why?

I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

net use \\<host> /delete should work, but many times it does not.

net stop workstation as @DaveInCaz offered works in such cases.

I have some why and hows I couldn't fit into a comment.

  • It's not enough to restart the Workstation service (e.g. from services.msc console)
    The service probably needs to be disabled for some short period of time. If you do this restart from a script, might be better to add a 1 second delay.

  • In cases when net use \\<host> /delete does not work because another program is still using that share, you can identify such program and remove the blocking handle without closing it. Use Sysinternals Process Explorer, press Ctrl+F for search and enter the name of host machine owning such share. Click on each result, program window behind search dialog jumps to found program's handle. Right click that handle and select Close Handle. (or just close such program if you can) This works only in regular cases where there really is a program blocking the share disconnect. Not in those weird cases when it's blocked for no reason.

  • elevated account has it's own environment. This brings some unexpected behavior.
    If you do net use command in an elevated cmd/PS console, it will not affect which user will Windows Explorer use to access the share.
    And also other way around, if you run a program from the share and the program will ask and get elevated access, that program will loose connection to that share and any files it might need to run. You need to run net use from elevated cmd/PS to create an elevated share connection to that share.

  • Removing Recent folders from Quick Access in Windows Explorer (top of left panel) might help in certain cases.
    If the Host you are connecting to offers different access levels based on user, and/or has a Guest user (anonymous) share access, this is a situation you might often run into.
    When you access a share using your username, folder inside such share might get assigned to Quick Access panel as a Recent item. When you open Windows Explorer after restart, Recent items inside Quick Access will be checked and a connection will be made to the Host machine and will stay open in form of a MUP. If your share accepts both authorized and anonymous connections, just opening Windows Explorer will create anonymous connection and when you click on a share which needs authorization, you will not get credential dialog but an error.

How to change Bootstrap's global default font size?

Bootstrap uses the variable:

$font-size-base: 1rem; // Assumes the browser default, typically 16px

I don't recommend mucking with this, but you can. Best practice is to override the browser default base font size with:

html {
  font-size: 14px;
}

Bootstrap will then take that value and use it via rems to set values for all kinds of things.

Upload folder with subfolders using S3 and the AWS console

You can't upload nested structures like that through the online tool. I'd recommend using something like Bucket Explorer for more complicated uploads.

How do you convert a jQuery object into a string?

The accepted answer doesn't cover text nodes (undefined is printed out).

This code snippet solves it:

_x000D_
_x000D_
var htmlElements = $('<p><a href="http://google.com">google</a></p>??<p><a href="http://bing.com">bing</a></p>'),_x000D_
    htmlString = '';_x000D_
    _x000D_
htmlElements.each(function () {_x000D_
    var element = $(this).get(0);_x000D_
_x000D_
    if (element.nodeType === Node.ELEMENT_NODE) {_x000D_
        htmlString += element.outerHTML;_x000D_
    }_x000D_
    else if (element.nodeType === Node.TEXT_NODE) {_x000D_
        htmlString += element.nodeValue;_x000D_
    }_x000D_
});_x000D_
_x000D_
alert('String html: ' + htmlString);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How do you completely remove the button border in wpf?

Programmatically, you can do this:

btn.BorderBrush = new SolidColorBrush(Colors.Transparent);

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

A very simple solution is to add the database name with your table name like if your DB name is DBMS and table is info then it will be DBMS.info for any query.

If your query is

select * from STUDENTREC where ROLL_NO=1;

it might show an error but

select * from DBMS.STUDENTREC where ROLL_NO=1; 

it doesn't because now actually your table is found.

How to get the last day of the month?

Here is another answer. No extra packages required.

datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)

Get the first day of the next month and subtract a day from it.

How do I convert a file path to a URL in ASP.NET

I've accepted Fredriks answer as it appears to solve the problem with the least amount of effort however the Request object doesn't appear to conatin the ResolveUrl method. This can be accessed through the Page object or an Image control object:

myImage.ImageUrl = Page.ResolveUrl(photoURL);
myImage.ImageUrl = myImage.ResolveUrl(photoURL);

An alternative, if you are using a static class as I am, is to use the VirtualPathUtility:

myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);

How to test android apps in a real device with Android Studio?

To test an android apps in a real device with Android Studio, You must keep two things in mind

  1. You should enable USB debugging option on your android phone.
  2. You must have driver installed on your computer.

Now , let me tell you how you can enable USB debugging on your android phone:

  1. Go to Settings on your android phone
  2. Scroll down to the bottom and click on About phone
  3. On this menu also scroll down to the bottom, you should see something Build number
  4. Click on Build number 7 times
  5. Now your Developer Option enables, once you done click on back button and you should see a new option on your android screen i.e. Developer Options
  6. Click On Developer Options
  7. Scroll down until you see USB Debugging
  8. Go ahead and click the check box next to the USB debugging
  9. Now your USB Debugging option enables.
  10. Connect your android device to your computer with the help of USB connector.

Now let me tell you how you can download the driver on your Windows PC:

  1. Your windows machine need a software called driver to communicate with your phone.
  2. Go To OEM USB Driver Website to install your appropriate driver
  3. Scroll down and select the driver appropriate for your device. Check the screen shoot
  4. Once you download it , you have to unzip your file
  5. After Installing Google USB Driver, close SDK Manager window, Connect your phone or tablet through USB cable to your laptop or PC.
  6. Now click on My Computer (Windows 7) (or) This PC(Windows 8.1).Select Manage.
  7. Select Device Manager –> Portable Devices –> Your Device Name
  8. Right Click on Your Device Name and Select Browse My Computer For Driver Software.
  9. Point it to C:\Users\YourUserName\AppData\Local\Android\sdk\extras\google\usb_driver. Hit Next and Finish.
  10. Now Hit Run Button after selecting Your Project in Project Explorer in Android studio. Choose your device and press OK.

Comparing two collections for equality irrespective of the order of items in them

If you use Shouldly, you can use ShouldAllBe with Contains.

collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1.ShouldAllBe(item=>collection2.Contains(item)); // true

And finally, you can write an extension.

public static class ShouldlyIEnumerableExtensions
{
    public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)
    {
        list.ShouldAllBe(l => equivalent.Contains(l));
    }
}

UPDATE

A optional parameter exists on ShouldBe method.

collection1.ShouldBe(collection2, ignoreOrder: true); // true

Change mysql user password using command line

As of MySQL 5.7.6, use ALTER USER

Example:

ALTER USER 'username' IDENTIFIED BY 'password';

Because:

  • SET PASSWORD ... = PASSWORD('auth_string') syntax is deprecated as of MySQL 5.7.6 and will be removed in a future MySQL release.

  • SET PASSWORD ... = 'auth_string' syntax is not deprecated, but ALTER USER is now the preferred statement for assigning passwords.

Sleep function in Windows, using C

Use:

#include <windows.h>

Sleep(sometime_in_millisecs); // Note uppercase S

And here's a small example that compiles with MinGW and does what it says on the tin:

#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep(3000); // Sleep three seconds
    printf("sleep ended\n");
}

How can I get query parameters from a URL in Vue.js?

You can use vue-router.I have an example below:

url: www.example.com?name=john&lastName=doe

new Vue({
  el: "#app",
  data: {
    name: '',
    lastName: ''
  },
  beforeRouteEnter(to, from, next) {
      if(Object.keys(to.query).length !== 0) { //if the url has query (?query)
        next(vm => {
         vm.name = to.query.name
         vm.lastName = to.query.lastName
       })
    }
    next()
  }
})

Note: In beforeRouteEnter function we cannot access the component's properties like: this.propertyName.That's why i have pass the vm to next function.It is the recommented way to access the vue instance.Actually the vm it stands for vue instance

Conda command is not recognized on Windows 10

When you install anaconda on windows now, it doesn't automatically add Python or Conda.

If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt

enter image description here

Next, you can add Python and Conda to your path by using the setx command in your command prompt. enter image description here

Next close that command prompt and open a new one. Congrats you can now use conda and python

Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444

How to negate the whole regex?

Assuming you only want to disallow strings that match the regex completely (i.e., mmbla is okay, but mm isn't), this is what you want:

^(?!(?:m{2}|t)$).*$

(?!(?:m{2}|t)$) is a negative lookahead; it says "starting from the current position, the next few characters are not mm or t, followed by the end of the string." The start anchor (^) at the beginning ensures that the lookahead is applied at the beginning of the string. If that succeeds, the .* goes ahead and consumes the string.

FYI, if you're using Java's matches() method, you don't really need the the ^ and the final $, but they don't do any harm. The $ inside the lookahead is required, though.

BASH Syntax error near unexpected token 'done'

Might help someone else : I encountered the same kind of issues while I had done some "copy-paste" from a side Microsoft Word document, where I took notes, to my shell script(s).

Re-writing, manually, the exact same code in the script just solved this.

It was quite un-understandable at first, I think Word's hidden characters and/or formatting were the issue. Obvious but not see-able ... I lost about one hour on this (I'm no shell expert, as you might guess ...)

jQuery Event : Detect changes to the html/text of a div

Following code works for me.

$("body").on('DOMSubtreeModified', "mydiv", function() {
    alert('changed');
});

Hope it will help someone :)

CSS Div Background Image Fixed Height 100% Width

But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

so it's better to use background:cover and set with media queries specific height's for popular resolutions.

How to simulate a button click using code?

If you do not use the sender argument, why not refactor the button handler implementation to separate function, and call it from wherever you want (from the button handler and from the other place).

Anyway, it is a better and cleaner design - a code that needs to be called on button handler AND from some other places deserves to be refactored to own function. Plus it will help you separate UI handling from application logic code. You will also have a nice name to the function, not just onDateSelectedButtonClick().

How to convert local time string to UTC?

First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See its documentation.

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.

Finally, use datetime.astimezone() method to convert the datetime to UTC.

Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

from datetime import datetime   
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

From there, you can use the strftime() method to format the UTC datetime as needed:

utc_dt.strftime("%Y-%m-%d %H:%M:%S")

Put search icon near textbox using bootstrap

Here are three different ways to do it:

screenshot

Here's a working Demo in Fiddle Of All Three

Validation:

You can use native bootstrap validation states (No Custom CSS!):

<div class="form-group has-feedback">
    <label class="control-label" for="inputSuccess2">Name</label>
    <input type="text" class="form-control" id="inputSuccess2"/>
    <span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>

For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box

Input Group:

You can use the .input-group class like this:

<div class="input-group">
    <input type="text" class="form-control"/>
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box

Unstyled Input Group:

You can still use .input-group for positioning but just override the default styling to make the two elements appear separate.

Use a normal input group but add the class input-group-unstyled:

<div class="input-group input-group-unstyled">
    <input type="text" class="form-control" />
    <span class="input-group-addon">
        <i class="fa fa-search"></i>
    </span>
</div>

Then change the styling with the following css:

.input-group.input-group-unstyled input.form-control {
    -webkit-border-radius: 4px;
       -moz-border-radius: 4px;
            border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
    border-radius: 4px;
    border: 0px;
    background-color: transparent;
}

Also, these solutions work for any input size

Examples of good gotos in C or C++

@fizzer.myopenid.com: your posted code snippet is equivalent to the following:

    while (system_call() == -1)
    {
        if (errno != EINTR)
        {
            // handle real errors

            break;
        }
    }

I definitely prefer this form.

Error Message: Type or namespace definition, or end-of-file expected

This line:

public  object Hours { get; set; }}

Your have a redundand } at the end

Python - add PYTHONPATH during command line module run

You may try this to execute a function inside your script

python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"

Bash scripting, multiple conditions in while loop

Try:

while [ $stats -gt 300 -o $stats -eq 0 ]

[ is a call to test. It is not just for grouping, like parentheses in other languages. Check man [ or man test for more information.

How to change the type of a field?

For string to int conversion.

db.my_collection.find().forEach( function(obj) {
    obj.my_value= new NumberInt(obj.my_value);
    db.my_collection.save(obj);
});

For string to double conversion.

    obj.my_value= parseInt(obj.my_value, 10);

For float:

    obj.my_value= parseFloat(obj.my_value);

Adding iOS UITableView HeaderView (not section header)

You can also simply create ONLY a UIView in Interface builder and drag & drop the ImageView and UILabel (to make it look like your desired header) and then use that.

Once your UIView looks like the way you want it too, you can programmatically initialize it from the XIB and add to your UITableView. In other words, you dont have to design the ENTIRE table in IB. Just the headerView (this way the header view can be reused in other tables as well)

For example I have a custom UIView for one of my table headers. The view is managed by a xib file called "CustomHeaderView" and it is loaded into the table header using the following code in my UITableViewController subclass:

-(UIView *) customHeaderView {
    if (!customHeaderView) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil];
    }

    return customHeaderView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set the CustomerHeaderView as the tables header view 
    self.tableView.tableHeaderView = self.customHeaderView;
}

Problems with jQuery getJSON using local files in Chrome

@Mike On Mac, type this in Terminal:

open -b com.google.chrome --args --disable-web-security

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

I found a particular edge case where I was using the tini init in an alpine container, but since I was not using the statically linked version, and Alpine uses musl libc rather than GNU LibC library installed by default, it was crashing with the very same error message.

Had I understood this and also taken time to read the documentation properly, I would have found Tini Static, which upon changing to, resolved my problem.

MySQL direct INSERT INTO with WHERE clause

Example of how to perform a INSERT INTO SELECT with a WHERE clause.

INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

What operator is <> in VBA

It means not equal to, as the others said..

I just wanted to say that I read that as "greater than or lesser than".

e.g.

let x = 12

if x <> 0 then
    //code

In this case 'x' is greater than (that's the '>' symbol) 0.

Hope this helps. :D

Get remote registry value

For remote registry you have to use .NET with powershell 2.0

$w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer1)
$keypath = 'SOFTWARE\Veritas\NetBackup\CurrentVersion'
$netbackup = $w32reg.OpenSubKey($keypath)
$NetbackupVersion1 = $netbackup.GetValue('PackageVersion')

How to use Morgan logger?

You might want to try using mongo-morgan-ext

The usage is:

var logger = require('mongo-morgan-ext');

var db = 'mongodb://localhost:27017/MyDB';

var collection = 'Logs'

var skipfunction = function(req, res) {

return res.statusCode > 399;
} //Thiw would skip if HTTP request response is less than 399 i.e no errors.

app.use(logger(db,collection,skipfunction)); //In your express-application

The expected output is

{
    "RequestID": "",
    "status": "",
    "method": "",
    "Remote-user": "",
    "Remote-address": "",
    "URL": "",
    "HTTPversion": "",
    "Response-time": "",
    "date":"",
    "Referrer": "",
    "REQUEST": { //10
        "Accept": "",
        "Accept-Charset": "",
        "Accept-Encoding": "",
        "Accept-Language": "",
        "Authorization": "",
        "Cache-Control": "",
        "Connection": "",
        "Cookie": "",
        "Content-Length": "",
        "Content-MD5": "",
        "Content-Type": "",
        "Expect": "",
        "Forwarded": "",
        "From": "",
        "Host": "",
        "Max-Forwards": "",
        "Origin": "",
        "Pragma": "",
        "Proxy-Authorization": "",
        "Range": "",
        "TE": "",
        "User-Agent": "",
        "Via": "",
        "Warning": "",
        "Upgrade": "",
        "Referer": "",
        "Date": "",
        "X-requested-with": "",
        "X-Csrf-Token": "",
        "X-UIDH": "",
        "Proxy-Connection": "",
        "X-Wap-Profile": "",
        "X-ATT-DeviceId": "",
        "X-Http-Method-Override":"",
        "Front-End-Https": "",
        "X-Forwarded-Proto": "",
        "X-Forwarded-Host": "",
        "X-Forwarded-For": "",
        "DNT": "",
        "Accept-Datetime": "",
        "If-Match": "",
        "If-Modified-Since": "",
        "If-None-Match": "",
        "If-Range": "",
        "If-Unmodified-Since": ""
    },
    "RESPONSE": {
        "Status": "",
        "Content-MD5":"",
        "X-Frame-Options": "",
        "Accept-Ranges": "",
        "Age": "",
        "Allow": "",
        "Cache-Control": "",
        "Connection": "",
        "Content-Disposition": "",
        "Content-Encoding": "",
        "Content-Language": "",
        "Content-Length": "",
        "Content-Location": "",
        "Content-Range": "",
        "Content-Type":"",
        "Date":"",
        "Last-Modified": "",
        "Link": "",
        "Location": "",
        "P3P": "",
        "Pragma": "",
        "Proxy-Authenticate": "",
        "Public-Key-Pins": "",
        "Retry-After": "",
        "Server": "",
        "Trailer": "",
        "Transfer-Encoding": "",
        "TSV": "",
        "Upgrade": "",
        "Vary": "",
        "Via": "",
        "Warning": "",
        "WWW-Authenticate": "",
        "Expires": "",
        "Set-Cookie": "",
        "Strict-Transport-Security": "",
        "Refresh":"",
        "Access-Control-Allow-Origin": "",
        "X-XSS-Protection": "",
        "X-WebKit-CSP":"",
        "X-Content-Security-Policy": "",
        "Content-Security-Policy": "",
        "X-Content-Type-Options": "",
        "X-Powered-By": "",
        "X-UA-Compatible": "",
        "X-Content-Duration": "",
        "Upgrade-Insecure-Requests": "",
        "X-Request-ID": "",
        "ETag": "",
        "Accept-Patch": ""
    }

}

How can I count the occurrences of a list item?

Below are the three solutions:

Fastest is using a for loop and storing it in a Dict.

import time
from collections import Counter


def countElement(a):
    g = {}
    for i in a:
        if i in g: 
            g[i] +=1
        else: 
            g[i] =1
    return g


z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4]


#Solution 1 - Faster
st = time.monotonic()
for i in range(1000000):
    b = countElement(z)
et = time.monotonic()
print(b)
print('Simple for loop and storing it in dict - Duration: {}'.format(et - st))

#Solution 2 - Fast
st = time.monotonic()
for i in range(1000000):
    a = Counter(z)
et = time.monotonic()
print (a)
print('Using collections.Counter - Duration: {}'.format(et - st))

#Solution 3 - Slow
st = time.monotonic()
for i in range(1000000):
    g = dict([(i, z.count(i)) for i in set(z)])
et = time.monotonic()
print(g)
print('Using list comprehension - Duration: {}'.format(et - st))

Result

#Solution 1 - Faster
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3}
Simple for loop and storing it in dict - Duration: 12.032000000000153
#Solution 2 - Fast
Counter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1})
Using collections.Counter - Duration: 15.889999999999418
#Solution 3 - Slow
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1}
Using list comprehension - Duration: 33.0

Using a SELECT statement within a WHERE clause

The principle of subqueries is not at all bad, but I don't think that you should use it in your example. If I understand correctly you want to get the maximum score for each date. In this case you should use a GROUP BY.

Javascript: how to validate dates in format MM-DD-YYYY?

How about validating dates in "ANY" date format? I've been using the DateJS library and adding it to existing forms to ensure that I get valid dates & times formatted the way that I want. The user can even enter things like "now" and "tomorrow" and it will be converted into a valid date.

Here's the dateJS library: http://www.datejs.com/

and here's a jQuery tip that I wrote: http://www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm

Google Maps JS API v3 - Simple Multiple Marker Example

This is the simplest I could reduce it to:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

? Edit/fork on a Codepen ?

SCREENSHOT

Google Maps Multiple Markers

There is some closure magic happening when passing the callback argument to the addListener method. This can be quite a tricky topic if you are not familiar with how closures work. I would suggest checking out the following Mozilla article for a brief introduction if it is the case:

? Mozilla Dev Center: Working with Closures

How do I get the application exit code from a Windows command line?

A pseudo environment variable named errorlevel stores the exit code:

echo Exit Code is %errorlevel%

Also, the if command has a special syntax:

if errorlevel

See if /? for details.

Example

@echo off
my_nify_exe.exe
if errorlevel 1 (
   echo Failure Reason Given is %errorlevel%
   exit /b %errorlevel%
)

Warning: If you set an environment variable name errorlevel, %errorlevel% will return that value and not the exit code. Use (set errorlevel=) to clear the environment variable, allowing access to the true value of errorlevel via the %errorlevel% environment variable.

ImportError: cannot import name main when running pip --version command in windows7 32 bit

On Windows 10, I used the following commands to downgrade pip:

python -m pip uninstall pip
python -m pip install pip==9.0.3

This should also work on Linux and Mac too.

Set a default parameter value for a JavaScript function

I find something simple like this to be much more concise and readable personally.

function pick(arg, def) {
   return (typeof arg == 'undefined' ? def : arg);
}

function myFunc(x) {
  x = pick(x, 'my default');
} 

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

The performance impact of using instanceof in Java

instanceof is very efficient, so your performance is unlikely to suffer. However, using lots of instanceof suggests a design issue.

If you can use xClass == String.class, this is faster. Note: you don't need instanceof for final classes.

How to get on scroll events?

You could use a @HostListener decorator. Works with Angular 4 and up.

import { HostListener } from '@angular/core';

@HostListener("window:scroll", []) onWindowScroll() {
    // do some stuff here when the window is scrolled
    const verticalOffset = window.pageYOffset 
          || document.documentElement.scrollTop 
          || document.body.scrollTop || 0;
}

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

Cannot invoke an expression whose type lacks a call signature

TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple and Pear don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean member. Because of structural typing, you don' need to inherit Apple and Pear from such an interface.

There are different ways to assign such a compatible type:

Assign type during variable declaration

This statement is implicitly typed to Apple[] | Pear[]:

const fruits = fruitBasket[key];

You can simply use a compatible type explicitly in in your variable declaration:

const fruits: { isDecayed: boolean }[] = fruitBasket[key];

For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple and Pear interfaces don't need to be changed):

type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];

Cast to compatible type for the operation

The problem with the given solution is that it changes the type of the fruits variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits:

const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

Or with the reusable Fruit type:

type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

The advantage of this solution is that both, fruits and freshFruits will be of type Apple[] | Pear[].

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

IMHO the pervasive, implicit localization in Java is its single largest design flaw. It may be intended for user interfaces, but frankly, who really uses Java for user interfaces today except for some IDEs where you can basically ignore localization because programmers aren't exactly the target audience for it. You can fix it (especially on Linux servers) by:

  • export LC_ALL=C TZ=UTC
  • set your system clock to UTC
  • never use localized implementations unless absolutely necessary (ie for display only)

To the Java Community Process members I recommend:

  • make localized methods, not the default, but require the user to explicitly request localization.
  • use UTF-8/UTC as the FIXED default instead because that's simply the default today. There is no reason to do something else, except if you want to produce threads like this.

I mean, come on, aren't global static variables an anti-OO pattern? Nothing else is those pervasive defaults given by some rudimentary environment variables.......

C++ Array of pointers: delete or delete []?

To simplify the answare let's look on the following code:

#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
private:
    int m_id;
    static int count;
public:
    A() {count++; m_id = count;}
    A(int id) { m_id = id; }
    ~A() {cout<< "Destructor A "   <<m_id<<endl; }
};

int A::count = 0;

void f1()
{   
    A* arr = new A[10];
    //delete operate only one constructor, and crash!
    delete arr;
    //delete[] arr;
}

int main()
{
    f1();
    system("PAUSE");
    return 0;
}

The output is: Destructor A 1 and then it's crashing (Expression: _BLOCK_TYPE_IS_VALID(phead- nBlockUse)).

We need to use: delete[] arr; becuse it's delete the whole array and not just one cell!

try to use delete[] arr; the output is: Destructor A 10 Destructor A 9 Destructor A 8 Destructor A 7 Destructor A 6 Destructor A 5 Destructor A 4 Destructor A 3 Destructor A 2 Destructor A 1

The same principle is for an array of pointers:

void f2()
{
    A** arr = new A*[10];
    for(int i = 0; i < 10; i++)
    {
        arr[i] = new A(i);
    }
    for(int i = 0; i < 10; i++)
    {
        delete arr[i];//delete the A object allocations.
    }

    delete[] arr;//delete the array of pointers
}

if we'll use delete arr instead of delete[] arr. it will not delete the whole pointers in the array => memory leak of pointer objects!

Proper usage of .net MVC Html.CheckBoxFor

I was looking for the solution to show the label dynamically from database like this:

checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database

So none of the above solution worked for me so I used like this:

 @Html.CheckBoxFor(m => m.Option1, new { @class = "options" }) 
 <label for="Option1">@Model.Option1Text</label>

 @Html.CheckBoxFor(m => m.Option2, new { @class = "options" }) 
 <label for="Option2">@Mode2.Option1Text</label>

In this way when user will click on label, checkbox will be selected.

Might be it can help someone.

Round a divided number in Bash

To do rounding up in truncating arithmetic, simply add (denom-1) to the numerator.

Example, rounding down:

N/2
M/5
K/16

Example, rounding up:

(N+1)/2
(M+4)/5
(K+15)/16

To do round-to-nearest, add (denom/2) to the numerator (halves will round up):

(N+1)/2
(M+2)/5
(K+8)/16

How to remove the first character of string in PHP?

use mb_substr function

    mb_substr("?abc", 1);

How to check whether the user uploaded a file in PHP?

In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully. https://www.php.net/manual/en/reserved.variables.files.php#109648

if ( boolval( $_FILES['image']['error'] === 0 ) ) {
    // ...
}

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

How to generate unique ID with node.js

nanoid achieves exactly the same thing that you want.

Example usage:

const { nanoid } = require("nanoid")

console.log(nanoid())
//=> "n340M4XJjATNzrEl5Qvsh"

Easy way to convert Iterable to Collection

Since RxJava is a hammer and this kinda looks like a nail, you can do

Observable.from(iterable).toList().toBlocking().single();

What is the use of a cursor in SQL Server?

Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.

for ex:

declare @tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into @tab values('Cricket','R11')
insert into @tab values('VollyBall','R12')

declare @game  varchar(20)
declare @Rollno varchar(20)

declare cur2 cursor for select game,rollno from @tab 

open cur2

fetch next from cur2 into @game,@rollno

WHILE   @@FETCH_STATUS = 0   
begin

print @game

print @rollno

FETCH NEXT FROM cur2 into @game,@rollno

end

close cur2

deallocate cur2

How do I force a favicon refresh?

If you are just interested in debugging it to make sure it has changed, you can just add a dummy entry to your /etc/hosts file and hit the new URL. That favicon wouldnt be cached already and you can make sure you new one is working.

Short of changing the name of the favicon, there is no way you can force your users to get a new copy

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

I upgraded to Windows 10 x64 (from Windows 7 x64), had a VirtualBox Windows 10 x64 VM, but got the VT-x error. My BIOS was enabled, settings - everything in this post was addressed, but still got the VT-x error.

What fixed it for me was to go to Lenovo and install the latest BIOS for my W550s ThinkPad. Once the upgrade was installed, VirtualBox gave me the x64 options again with no more VT-x errors.

If you are running a W550s, the BIOS version I installed was from September 2015, "BIOS Update Utility" n11uj05w.exe, version 1.10 from the Lenovo website.

Global environment variables in a shell script

Run your script with .

. myscript.sh

This will run the script in the current shell environment.

export governs which variables will be available to new processes, so if you say

FOO=1
export BAR=2
./runScript.sh

then $BAR will be available in the environment of runScript.sh, but $FOO will not.

MySQL: Large VARCHAR vs. TEXT?

Disclaimer: I'm not a MySQL expert ... but this is my understanding of the issues.

I think TEXT is stored outside the mysql row, while I think VARCHAR is stored as part of the row. There is a maximum row length for mysql rows .. so you can limit how much other data you can store in a row by using the VARCHAR.

Also due to VARCHAR forming part of the row, I suspect that queries looking at that field will be slightly faster than those using a TEXT chunk.

Sort an array in Java

MOST EFFECTIVE WAY!

public static void main(String args[])
{
    int [] array = new int[10];//creates an array named array to hold 10 int's
    for(int x: array)//for-each loop!
      x = ((int)(Math.random()*100+1));
    Array.sort(array);
    for(int x: array)
      System.out.println(x+" ");
}

Call a function from another file?

You don't have to add file.py.

Just keep the file in the same location with the file from where you want to import it. Then just import your functions:

from file import a, b

replace NULL with Blank value or Zero in sql server

Replace Null Values as Empty: ISNULL('Value','')

Replace Null Values as 0: ISNULL('Value',0)

Sequence Permission in Oracle

To grant a permission:

grant select on schema_name.sequence_name to user_or_role_name;

To check which permissions have been granted

select * from all_tab_privs where TABLE_NAME = 'sequence_name'

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

Get all photos from Instagram which have a specific hashtag with PHP

There is the instagram public API's tags section that can help you do this.

Convert string to Time

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

CSS media queries: max-width OR max-height

CSS Media Queries & Logical Operators: A Brief Overview ;)

The quick answer.

Separate rules with commas: @media handheld, (min-width: 650px), (orientation: landscape) { ... }

The long answer.

There's a lot here, but I've tried to make it information dense, not just fluffy writing. It's been a good chance to learn myself! Take the time to systematically read though and I hope it will be helpful.


Media Queries

Media queries essentially are used in web design to create device- or situation-specific browsing experiences; this is done using the @media declaration within a page's CSS. This can be used to display a webpage differently under a large number of circumstances: whether you are on a tablet or TV with different aspect ratios, whether your device has a color or black-and-white screen, or, perhaps most frequently, when a user changes the size of their browser or switches between browsing devices with varying screen sizes (very generally speaking, designing like this is referred to as Responsive Web Design)

Logical Operators

In designing for these situations, there appear to be four Logical Operators that can be used to require more complex combinations of requirements when targeting a variety of devices or viewport sizes.

(Note: If you don't understand the the differences between media rules, media queries, and feature queries, browse the bottom section of this answer first to get a bit better acquainted with the terminology associated with media query syntax

1. AND (and keyword)

Requires that all conditions specified must be met before the styling rules will take effect.

@media screen and (min-width: 700px) and (orientation: landscape) { ... }

The specified styling rules won't go into place unless all of the following evaluate as true:

  • The media type is 'screen' and
  • The viewport is at least 700px wide and
  • Screen orientation is currently landscape.

Note: I believe that used together, these three feature queries make up a single media query.

2. OR (Comma-separated lists)

Rather than an or keyword, comma-separated lists are used in chaining multiple media queries together to form a more complex media rule

@media handheld, (min-width: 650px), (orientation: landscape) { ... }

The specified styling rules will go into effect once any one media query evaluates as true:

  1. The media type is 'handheld' or
  2. The viewport is at least 650px wide or
  3. Screen orientation is currently landscape.

3. NOT (not keyword)

The not keyword can be used to negate a single media query (and NOT a full media rule--meaning that it only negates entries between a set of commas and not the full media rule following the @media declaration).

Similarly, note that the not keyword negates media queries, it cannot be used to negate an individual feature query within a media query.*

@media not screen and (min-resolution: 300dpi), (min-width: 800px) { ... }

The styling specified here will go into effect if

  1. The media type AND min-resolution don't both meet their requirements ('screen' and '300dpi' respectively) or
  2. The viewport is at least 800 pixels wide.

In other words, if the media type is 'screen' and the min-resolution is 300 dpi, the rule will not go into effect unless the min-width of the viewport is at least 800 pixels.

(The not keyword can be a little funky to state. Let me know if I can do better. ;)

4. ONLY (only keyword)

As I understand it, the only keyword is used to prevent older browsers from misinterpreting newer media queries as the earlier-used, narrower media type. When used correctly, older/non-compliant browsers should just ignore the styling altogether.

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

An older / non-compliant browser would just ignore this line of code altogether, I believe as it would read the only keyword and consider it an incorrect media type. (See here and here for more info from smarter people)

FOR MORE INFO

For more info (including more features that can be queried), see: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#Logical_operators


Understanding Media Query Terminology

Note: I needed to learn the following terminology for everything here to make sense, particularly concerning the not keyword. Here it is as I understand it:

A media rule (MDN also seems to call these media statements) includes the term @media with all of its ensuing media queries

@media all and (min-width: 800px)

@media only screen and (max-resolution:800dpi), not print

@media screen and (min-width: 700px), (orientation: landscape)

@media handheld, (min-width: 650px), (min-aspect-ratio: 1/1)

A media query is a set of feature queries. They can be as simple as one feature query or they can use the and keyword to form a more complex query. Media queries can be comma-separated to form more complex media rules (see the or keyword above).

screen (Note: Only one feature query in use here.)

only screen

only screen and (max-resolution:800dpi)

only tv and (device-aspect-ratio: 16/9) and (color)

NOT handheld, (min-width: 650px). (Note the comma: there are two media queries here.)

A feature query is the most basic portion of a media rule and simply concerns a given feature and its status in a given browsing situation.

screen

(min-width: 650px)

(orientation: landscape)

(device-aspect-ratio: 16/9)


Code snippets and information derived from:

CSS media queries by Mozilla Contributors (licensed under CC-BY-SA 2.5). Some code samples were used with minor alterations to (hopefully) increase clarity of explanation.

Difference between List, List<?>, List<T>, List<E>, and List<Object>

Theory

String[] can be cast to Object[]

but

List<String> cannot be cast to List<Object>.

Practice

For lists it is more subtle than that, because at compile time the type of a List parameter passed to a method is not checked. The method definition might as well say List<?> - from the compiler's point of view it is equivalent. This is why the OP's example #2 gives runtime errors not compile errors.

If you handle a List<Object> parameter passed to a method carefully so you don't force a type check on any element of the list, then you can have your method defined using List<Object> but in fact accept a List<String> parameter from the calling code.

A. So this code will not give compile or runtime errors and will actually (and maybe surprisingly?) work:

public static void main(String[] args) {
    List argsList = new ArrayList<String>();
    argsList.addAll(Arrays.asList(args));
    test(argsList);  // The object passed here is a List<String>
}

public static void test(List<Object> set) {
    List<Object> params = new ArrayList<>();  // This is a List<Object>
    params.addAll(set);       // Each String in set can be added to List<Object>
    params.add(new Long(2));  // A Long can be added to List<Object>
    System.out.println(params);
}

B. This code will give a runtime error:

public static void main(String[] args) {
    List argsList = new ArrayList<String>();
    argsList.addAll(Arrays.asList(args));
    test1(argsList);
    test2(argsList);
}

public static void test1(List<Object> set) {
    List<Object> params = set;  // Surprise!  Runtime error
}

public static void test2(List<Object> set) {
    set.add(new Long(2));       // Also a runtime error
}

C. This code will give a runtime error (java.lang.ArrayStoreException: java.util.Collections$UnmodifiableRandomAccessList Object[]):

public static void main(String[] args) {
    test(args);
}

public static void test(Object[] set) {
    Object[] params = set;    // This is OK even at runtime
    params[0] = new Long(2);  // Surprise!  Runtime error
}

In B, the parameter set is not a typed List at compile time: the compiler sees it as List<?>. There is a runtime error because at runtime, set becomes the actual object passed from main(), and that is a List<String>. A List<String> cannot be cast to List<Object>.

In C, the parameter set requires an Object[]. There is no compile error and no runtime error when it is called with a String[] object as the parameter. That's because String[] casts to Object[]. But the actual object received by test() remains a String[], it didn't change. So the params object also becomes a String[]. And element 0 of a String[] cannot be assigned to a Long!

(Hopefully I have everything right here, if my reasoning is wrong I'm sure the community will tell me. UPDATED: I have updated the code in example A so that it actually compiles, while still showing the point made.)

PHP - Session destroy after closing browser

The best way is to close the session is: if there is no response for that session after particular interval of time. then close. Please see this post and I hope it will resolve the issue. "How to change the session timeout in PHP?"

Multiple submit buttons on HTML form – designate one button as default

Quick'n'dirty you could create an hidden duplicate of the submit-button, which should be used, when pressing enter.

Example CSS

input.hidden {
    width: 0px;
    height: 0px;
    margin: 0px;
    padding: 0px;
    outline: none;
    border: 0px;
}

Example HTML

<input type="submit" name="next" value="Next" class="hidden" />
<input type="submit" name="prev" value="Previous" />
<input type="submit" name="next" value="Next" />

If someone now hits enter in your form, the (hidden) next-button will be used as submitter.

Tested on IE9, Firefox, Chrome and Opera

SELECT query with CASE condition and SUM()

Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
       SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Minimal web server using netcat

LOL, a super lame hack, but at least curl and firefox accepts it:

while true ; do (dd if=/dev/zero count=10000;echo -e "HTTP/1.1\n\n $(date)") | nc -l  1500  ; done

You better replace it soon with something proper!

Ah yes, my nc were not exactly the same as yours, it did not like the -p option.

How to convert string to integer in PowerShell

You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):

$string = "1654"
$integer = [int]$string

$string + 1
# Outputs 16541

$integer + 1
# Outputs 1655

As an example, the following snippet adds, to each object in $fileList, an IntVal property with the integer value of the Name property, then sorts $fileList on this new property (the default is ascending), takes the last (highest IntVal) object's IntVal value, increments it and finally creates a folder named after it:

# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null

$highest = $fileList |
    Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
    Sort-Object IntVal |
    Select-Object -Last 1

$newName = $highest.IntVal + 1

New-Item $newName -ItemType Directory

Sort-Object IntVal is not needed so you can remove it if you prefer.

[int]::MaxValue = 2147483647 so you need to use the [long] type beyond this value ([long]::MaxValue = 9223372036854775807).

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to :

  • Stop the Oracle-related services (before deleting them from the registry).
  • In the registry, look not only for entries named "Oracle" but also e.g. for "ODP".

What is the mouse down selector in CSS?

I recently found out that :active:focus does the same thing in css as :active:hover if you need to override a custom css library, they might use both.

How to implement reCaptcha for ASP.NET MVC?

There are a few great examples:

This has also been covered before in this Stack Overflow question.

NuGet Google reCAPTCHA V2 for MVC 4 and 5

Class Not Found Exception when running JUnit test

I had faced the same issue. I solved it by removing the external JUnit jar dependency which I added by download from the internet externally. But then I went to project->properties->build path->add library->junit->choosed the version(ex junit4)->apply.

It automatically added the dependency. it solved my issue.

ES6 Class Multiple inheritance

Here's an awesome/really crappy way of extending multiple classes. I'm utilizing a couple functions that Babel put into my transpiled code. The function creates a new class that inherits class1, and class1 inherits class2, and so on. It has its issues, but a fun idea.

var _typeof = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? function (obj) {
  return typeof obj
} : function (obj) {
  return obj && typeof Symbol === 'function' && obj.constructor === Symbol ? 'symbol' : typeof obj
}

function _inherits (subClass, superClass) {
  if (typeof superClass !== 'function' && superClass !== null) {
    throw new TypeError('Super expression must either be null or a function, not ' + (
      typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)))
  }
  subClass.prototype = Object.create(
    superClass && superClass.prototype,
    {
      constructor: {
        value: subClass,
        enumerable: false,
        writable: true,
        configurable: true
      }
    })
  if (superClass) {
    Object.setPrototypeOf
    ? Object.setPrototypeOf(subClass, superClass)
    : subClass.__proto__ = superClass.__proto__  // eslint-disable-line no-proto
  }
}

function _m (...classes) {
  let NewSuperClass = function () {}
  let c1 = NewSuperClass
  for (let c of classes) {
    _inherits(c1, c)
    c1 = c
  }
  return NewSuperClass
}

import React from 'react'

/**
 * Adds `this.log()` to your component.
 * Log message will be prefixed with the name of the component and the time of the message.
 */
export default class LoggingComponent extends React.Component {
  log (...msgs) {
    if (__DEBUG__) {
      console.log(`[${(new Date()).toLocaleTimeString()}] [${this.constructor.name}]`, ...msgs)
    }
  }
}

export class MyBaseComponent extends _m(LoggingComponent, StupidComponent) {}

Set ANDROID_HOME environment variable in mac

If you try to run "adb devices" OR any other command and it says something like

zsh: command not found adb

It tells that you are using zsh shell and /.bash_profile won't work as it should. You will have to execute bash_profile everytime with source ~/.bash_profile command when you open terminal, and it isn't permanent.

To fix this run

nano ~/.zshrc

Terminal image

and then paste following commands at the end of the file

export ANDROID_HOME=/Users/{YourName}/Library/Android/sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/tools/bin:$PATH

NOTE: You can find Android Home url from Android Studio > Preferences System Settings > Android SDK > Android SDK Location textbox

To save it, hit Ctrl + X, type Y to save and then enter to keep the file name as it is.

Restart the terminal and try your commands again.

How to include external Python code to use in other files?

I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5. Happy coding!

Alternative #1

import textwrap 
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))

Alternative #2

with open('myfile.py') as f: exec(f.read())

How to get the current date without the time?

You can use DateTime.Now.ToShortDateString() like so:

var test = $"<b>Date of this report:</b> {DateTime.Now.ToShortDateString()}";

How to prevent a jQuery Ajax request from caching in Internet Explorer?

If you set unique parameters, then the cache does not work, for example:

$.ajax({
    url : "my_url",
    data : {
        'uniq_param' : (new Date()).getTime(),
        //other data
    }});

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

How do I vertically align text in a div?

Margin auto on a grid-item.

Similarly to Flexbox, applying margin auto on a grid-item centers it on both axes:

.container {
  display: grid;
}
.element {
  margin: auto;
}

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

Tesseract OCR simple example

Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing

Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.

Setup

To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.

Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.

VC++ Directories>Include Directories:

..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:

include

include

Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.

When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.

tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample

You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.

clientHeight/clientWidth returning different values on different browsers

Paul A is right about why the discrepancy exists but the solution offered by Ngm is wrong (in the sense of JQuery).

The equivalent of clientHeight and clientWidth in jquery (1.3) is

$(window).width(), $(window).height()

Android Bitmap to Base64 String

Try this, first scale your image to required width and height, just pass your original bitmap, required width and required height to the following method and get scaled bitmap in return:

For example: Bitmap scaledBitmap = getScaledBitmap(originalBitmap, 250, 350);

private Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight)
{
    int bWidth = b.getWidth();
    int bHeight = b.getHeight();

    int nWidth = bWidth;
    int nHeight = bHeight;

    if(nWidth > reqWidth)
    {
        int ratio = bWidth / reqWidth;
        if(ratio > 0)
        {
            nWidth = reqWidth;
            nHeight = bHeight / ratio;
        }
    }

    if(nHeight > reqHeight)
    {
        int ratio = bHeight / reqHeight;
        if(ratio > 0)
        {
            nHeight = reqHeight;
            nWidth = bWidth / ratio;
        }
    }

    return Bitmap.createScaledBitmap(b, nWidth, nHeight, true);
}

Now just pass your scaled bitmap to the following method and get base64 string in return:

For example: String base64String = getBase64String(scaledBitmap);

private String getBase64String(Bitmap bitmap)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

    byte[] imageBytes = baos.toByteArray();

    String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);

    return base64String;
}

To decode the base64 string back to bitmap image:

byte[] decodedByteArray = Base64.decode(base64String, Base64.NO_WRAP);
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedString.length);

How do I update the GUI from another thread?

Salvete! Having searched for this question, I found the answers by FrankG and Oregon Ghost to be the easiest most useful to me. Now, I code in Visual Basic and ran this snippet through a convertor; so I'm not sure quite how it turns out.

I have a dialog form called form_Diagnostics, which has a richtext box, called updateDiagWindow, which I am using as a sort of logging display. I needed to be able to update its text from all threads. The extra lines allow the window to automatically scroll to the newest lines.

And so, I can now update the display with one line, from anywhere in the entire program in the manner which you think it would work without any threading:

  form_Diagnostics.updateDiagWindow(whatmessage);

Main Code (put this inside of your form's class code):

#region "---------Update Diag Window Text------------------------------------"
// This sub allows the diag window to be updated by all threads
public void updateDiagWindow(string whatmessage)
{
    var _with1 = diagwindow;
    if (_with1.InvokeRequired) {
        _with1.Invoke(new UpdateDiagDelegate(UpdateDiag), whatmessage);
    } else {
        UpdateDiag(whatmessage);
    }
}
// This next line makes the private UpdateDiagWindow available to all threads
private delegate void UpdateDiagDelegate(string whatmessage);
private void UpdateDiag(string whatmessage)
{
    var _with2 = diagwindow;
    _with2.appendtext(whatmessage);
    _with2.SelectionStart = _with2.Text.Length;
    _with2.ScrollToCaret();
}
#endregion

Split an NSString to access one particular piece

Its working fine

NSString *dateString = @"10/10/2010";//Date 
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];

Why Choose Struct Over Class?

According to the very popular WWDC 2015 talk Protocol Oriented Programming in Swift (video, transcript), Swift provides a number of features that make structs better than classes in many circumstances.

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. (For the more technically minded, the exception to that is when capturing a struct inside a closure because then it is actually capturing a reference to the instance unless you explicitly mark it to be copied).

Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to create huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.

The talk lays out these scenarios where classes are preferred:

  • Copying or comparing instances doesn't make sense (e.g., Window)
  • Instance lifetime is tied to external effects (e.g., TemporaryFile)
  • Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)

It implies that structs should be the default and classes should be a fallback.

On the other hand, The Swift Programming Language documentation is somewhat contradictory:

Structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.

As a general guideline, consider creating a structure when one or more of these conditions apply:

  • The structure’s primary purpose is to encapsulate a few relatively simple data values.
  • It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
  • Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
  • The structure does not need to inherit properties or behavior from another existing type.

Examples of good candidates for structures include:

  • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
  • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
  • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

Here it is claiming that we should default to using classes and use structures only in specific circumstances. Ultimately, you need to understand the real world implication of value types vs. reference types and then you can make an informed decision about when to use structs or classes. Also, keep in mind that these concepts are always evolving and The Swift Programming Language documentation was written before the Protocol Oriented Programming talk was given.

Immutable vs Mutable types

Difference between Mutable and Immutable objects

Definitions

Mutable object: Object that can be changed after creating it.
Immutable object: Object that cannot be changed after creating it.

In python if you change the value of the immutable object it will create a new object.

Mutable Objects

Here are the objects in Python that are of mutable type:

  1. list
  2. Dictionary
  3. Set
  4. bytearray
  5. user defined classes

Immutable Objects

Here are the objects in Python that are of immutable type:

  1. int
  2. float
  3. decimal
  4. complex
  5. bool
  6. string
  7. tuple
  8. range
  9. frozenset
  10. bytes

Some Unanswered Questions

Questions: Is string an immutable type?
Answer: yes it is, but can you explain this: Proof 1:

a = "Hello"
a +=" World"
print a

Output

"Hello World"

In the above example the string got once created as "Hello" then changed to "Hello World". This implies that the string is of the mutable type. But it is not when we check its identity to see whether it is of a mutable type or not.

a = "Hello"
identity_a = id(a)
a += " World"
new_identity_a = id(a)
if identity_a != new_identity_a:
    print "String is Immutable"

Output

String is Immutable

Proof 2:

a = "Hello World"
a[0] = "M"

Output

TypeError 'str' object does not support item assignment

Questions: Is Tuple an immutable type?
Answer: yes, it is. Proof 1:

tuple_a = (1,)
tuple_a[0] = (2,)
print a

Output

'tuple' object does not support item assignment

Determine the line of code that causes a segmentation fault?

GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:

gcc program.c -g

Then use gdb:

$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>

Here is a nice tutorial to get you started with GDB.

Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.

How to insert the current timestamp into MySQL database using a PHP insert query

Forgot to put the variable in the sql statement without quotations.

 $update_query = 
      "UPDATE db.tablename SET insert_time=NOW() WHERE username='" .$somename."'";

How to set TLS version on apache HttpClient

Since this only came up hidden in comments, difficult to find as a solution:

You can use java -Dhttps.protocols=TLSv1,TLSv1.1, but you need to use also useSystemProperties()

client = HttpClientBuilder.create().useSystemProperties();

We use this setup in our system now as this enables us to set this only for some usage of the code. In our case we still have some Java 7 running and one API end point disallowed TLSv1, so we use java -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2 to enable current TLS versions. Thanks @jebeaudet for pointing in this direction.

Add a property to a JavaScript object using a variable as the name?

Related to the subject, not specifically for jquery though. I used this in ec6 react projects, maybe helps someone:

this.setState({ [`${name}`]: value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[name]));
    });

PS: Please mind the quote character.

How to install a specific version of package using Composer?

Suppose you want to install Laravel Collective. It's currently at version 6.x but you want version 5.8. You can run the following command:

composer require "laravelcollective/html":"^5.8.0"

A good example is shown here in the documentation: https://laravelcollective.com/docs/5.5/html

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

create a view on the custom cell in the table view and apply PanGestureRecognizer to the view on the cell.Add the buttons to the custom cell, when you swipe the view on the custom cell then the buttons on the custom cell will be visible.

 UIGestureRecognizer* recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    recognizer.delegate = self;
    [YourView addGestureRecognizer:recognizer];

And handle the panning on the view in the method

 if (recognizer.state == UIGestureRecognizerStateBegan) {
    // if the gesture has just started, record the current centre location
    _originalCenter = vwCell.center;
}

// 2
if (recognizer.state == UIGestureRecognizerStateChanged) {
    // translate the center
    CGPoint translation = [recognizer translationInView:self];
    vwCell.center = CGPointMake(_originalCenter.x + translation.x, _originalCenter.y);
    // determine whether the item has been dragged far enough to initiate  / complete
    _OnDragRelease = vwCell.frame.origin.x < -vwCell.frame.size.width / 2;

}

// 3
if (recognizer.state == UIGestureRecognizerStateEnded) {
    // the frame this cell would have had before being dragged
    CGPoint translation = [recognizer translationInView:self];

    if (_originalCenter.x+translation.x<22) {
          vwCell.center = CGPointMake(22, _originalCenter.y);
        IsvwRelease=YES;

    }
    CGRect originalFrame = CGRectMake(0, vwCell.frame.origin.y,
                                      vwCell.bounds.size.width, vwCell.bounds.size.height);
    if (!_deleteOnDragRelease) {
        // if the item is not being dragged far enough , snap back to the original location
        [UIView animateWithDuration:0.2
                         animations:^{
                             vwCell.frame = originalFrame;
                         }
         ];
    }
}

How to generate an MD5 file hash in JavaScript?

You can use crypto-js.

To use crypto-js, you need to load core.js then md5.js .

A list of URLs are here https://cdnjs.com/libraries/crypto-js

cryptojs is also available in zip form here https://code.google.com/archive/p/crypto-js/downloads

There is an answer from answerer 'amal' in 2013, that is similar to this but a)his link to md5.js no longer works b)he didn't load core.js beforehand, which is necessary.

<html>    
  <head> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>

  <script>
     var hash = CryptoJS.MD5("Message");
     console.log(hash);
  </script>

  </head>
  <body>

  </body>
</html>

Volley JsonObjectRequest Post request not working

All you need to do is to override getParams method in Request class. I had the same problem and I searched through the answers but I could not find a proper one. The problem is unlike get request, post parameters being redirected by the servers may be dropped. For instance, read this. So, don't risk your requests to be redirected by webserver. If you are targeting http://example/myapp , then mention the exact address of your service, that is http://example.com/myapp/index.php.
Volley is OK and works perfectly, the problem stems from somewhere else.

What is an alternative to execfile in Python 3?

As suggested on the python-dev mailinglist recently, the runpy module might be a viable alternative. Quoting from that message:

https://docs.python.org/3/library/runpy.html#runpy.run_path

import runpy
file_globals = runpy.run_path("file.py")

There are subtle differences to execfile:

  • run_path always creates a new namespace. It executes the code as a module, so there is no difference between globals and locals (which is why there is only a init_globals argument). The globals are returned.

    execfile executed in the current namespace or the given namespace. The semantics of locals and globals, if given, were similar to locals and globals inside a class definition.

  • run_path can not only execute files, but also eggs and directories (refer to its documentation for details).

Can't import org.apache.http.HttpResponse in Android Studio

in case you are going to start development, go fot OkHttp from square, otherwise if you need to keep your previous code running, then add legacy library to your project dependencies:

dependencies {
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

Insert the same fixed value into multiple rows

This is because in relational database terminology, what you want to do is not called "inserting", but "UPDATING" - you are updating an existing row's field from one value (NULL in your case) to "test"

UPDATE your_table SET table_column = "test" 
WHERE table_column = NULL 

You don't need the second line if you want to update 100% of rows.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Mine was different again. I was setting the user-agent like so:

    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

This was causing something on the web page to freak out and leak memory. Not sure why but removing this sorted the issue for me.

How to convert java.sql.timestamp to LocalDate (java8) java.time?

The accepted answer is not ideal, so I decided to add my 2 cents

timeStamp.toLocalDateTime().toLocalDate();

is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

The good solution is

timestamp.toInstant().atZone(zoneId).toLocalDate()

Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

The general approach should be

  1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
  2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

Using multiple .cpp files in c++ program?

You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

// main.cpp
#include "second.h"
int main () {
    secondFunction();
}

// second.h
void secondFunction();

// second.cpp
#include "second.h"
void secondFunction() {
   // do stuff
}

WHILE LOOP with IF STATEMENT MYSQL

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

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

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

Just for others:

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

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

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

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

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

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

Then use the following code in the SQL Query Window.

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

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

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

How to get response status code from jQuery.ajax?

jqxhr is a json object:

complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

see: jQuery ajax

so you would do:

jqxhr.status to get the status

How do I mock an open used in a with statement (using the Mock framework in Python)?

I might be a bit late to the game, but this worked for me when calling open in another module without having to create a new file.

test.py

import unittest
from mock import Mock, patch, mock_open
from MyObj import MyObj

class TestObj(unittest.TestCase):
    open_ = mock_open()
    with patch.object(__builtin__, "open", open_):
        ref = MyObj()
        ref.save("myfile.txt")
    assert open_.call_args_list == [call("myfile.txt", "wb")]

MyObj.py

class MyObj(object):
    def save(self, filename):
        with open(filename, "wb") as f:
            f.write("sample text")

By patching the open function inside the __builtin__ module to my mock_open(), I can mock writing to a file without creating one.

Note: If you are using a module that uses cython, or your program depends on cython in any way, you will need to import cython's __builtin__ module by including import __builtin__ at the top of your file. You will not be able to mock the universal __builtin__ if you are using cython.

How can I open a popup window with a fixed size using the HREF tag?

I can't comment on Esben Skov Pedersen's answer directly, but using the following notation for links:

<a href="javascript:window.open('http://www.websiteofyourchoice.com');">Click here</a>

In Internet Explorer, the new browser window appears, but the current window navigates to a page which says "[Object]". To avoid this, simple put a "void(0)" behind the JavaScript function.

Source: https://support.microsoft.com/en-us/kb/257321

Adding new column to existing DataFrame in Python pandas

One thing to note, though, is that if you do

df1['e'] = Series(np.random.randn(sLength), index=df1.index)

this will effectively be a left join on the df1.index. So if you want to have an outer join effect, my probably imperfect solution is to create a dataframe with index values covering the universe of your data, and then use the code above. For example,

data = pd.DataFrame(index=all_possible_values)
df1['e'] = Series(np.random.randn(sLength), index=df1.index)

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

GCC dump preprocessor defines

Late answer - I found the other answers useful - and wanted to add a bit extra.


How do I dump preprocessor macros coming from a particular header file?

echo "#include <sys/socket.h>" | gcc -E -dM -

or (thanks to @mymedia for the suggestion):

gcc -E -dM -include sys/socket.h - < /dev/null

In particular, I wanted to see what SOMAXCONN was defined to on my system. I know I could just open up the standard header file, but sometimes I have to search around a bit to find the header file locations. Instead I can just use this one-liner:

$ gcc -E -dM -include sys/socket.h - < /dev/null | grep SOMAXCONN
#define SOMAXCONN 128
$ 

Update int column in table with unique incrementing values

You can try :

DECLARE @counter int
SET @counter = 0
UPDATE [table]
SET [column] = @counter, @counter = @counter + 1```

Error in launching AVD with AMD processor

I faced the same problem recently.

I installed the HAXM installer on your SDK Manager:

Enter image description here

And then installed the latest Intel HAXM driver:

https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement

And voila!!! The emulator works like a charm :)

How is the java memory pool divided?

With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?

That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.

Graphviz: How to go from .dot to a graph?

dot file.dot -Tpng -o image.png

This works on Windows and Linux. Graphviz must be installed.

Python data structure sort list alphabetically

Python has a built-in function called sorted, which will give you a sorted list from any iterable you feed it (such as a list ([1,2,3]); a dict ({1:2,3:4}, although it will just return a sorted list of the keys; a set ({1,2,3,4); or a tuple ((1,2,3,4))).

>>> x = [3,2,1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]

Lists also have a sort method that will perform the sort in-place (x.sort() returns None but changes the x object) .

>>> x = [3,2,1]
>>> x.sort()
>>> x
[1, 2, 3]

Both also take a key argument, which should be a callable (function/lambda) you can use to change what to sort by.
For example, to get a list of (key,value)-pairs from a dict which is sorted by value you can use the following code:

>>> x = {3:2,2:1,1:5}
>>> sorted(x.items(), key=lambda kv: kv[1])  # Items returns a list of `(key,value)`-pairs
[(2, 1), (3, 2), (1, 5)]

How to create a Rectangle object in Java using g.fillRect method

You may try like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {
    g.drawRect (x, y, width, height);    //can use either of the two//
    g.fillRect (x, y, width, height);
    g.setColor(color);
  }

}

where x is x co-ordinate y is y cordinate color=the color you want to use eg Color.blue

if you want to use rectangle object you could do it like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {    
    Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
    g.setColor(color);
  }
}       

Using request.setAttribute in a JSP page

If you want your requests to persists try this:

example: on your JSP or servlet page

request.getSession().setAttribute("SUBFAMILY", subFam);

and on any receiving page use the below lines to retrieve your session and data:

SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");

How can I protect my .NET assemblies from decompilation?

One thing to keep in mind is that you want to do this in a way that makes business sense. To do that, you need to define your goals. So, exactly what are your goals?

Preventing piracy? That goal is not achievable. Even native code can be decompiled or cracked; the multitude of warez available online (even for products like Windows and Photoshop) is proof a determined hacker can always gain access.

If you can't prevent piracy, then how about merely reducing it? This, too, is misguided. It only takes one person cracking your code for it to be available to everyone. You have to be lucky every time. The pirates only have to be lucky once.

I put it to you the goal should be to maximize profits. You appear to believe that stopping piracy is necessary to this endeavor. It is not. Profit is simply revenue minus costs. Stopping piracy increases costs. It takes effort, which means adding cost somewhere in the process, and so reduces that side of the equation. Protecting your product also fails to increase your revenue. I know you look at all those pirates and see all the money you could make if only they would pay your license fees instead, but the reality is this will never happen. There is some hyperbole here, but it generally holds that pirates who are unable to crack your security will either find a similar product they can crack or do without. They will never buy it instead, and therefore they do not represent lost sales.

Additionally, securing your product actually reduces revenue. There are two reasons for this. One is the small percentage of customers who have trouble with your activation or security, and therefore decide not to buy again or ask for their money back. The other is the small percentage of people who actually try a pirated version of software to make sure it works before buying. Limiting the pirated distribution of your product (if you are somehow able to succeed at this) prevents these people from ever trying your product, and so they will never buy it. Moreover, piracy can also help your product spread to a wider audience, thus reaching more people who will be willing to pay for it.

A better strategy is to assume that your product will be pirated, and think about ways to take advantage of the situation. A couple more links on the topic:
How do i prevent my code from being stolen?
Securing a .NET Application

How to make an empty div take space

it works if you remove floating. http://jsbin.com/izoca/2/edit

with floats it only works if theres some content e.g. &nbsp;