Programs & Examples On #Coolstorage

Vici CoolStorage is a fully typed Object Relational Mapping library for .NET 3.5, Windows Phone and MonoTouch. CoolStorage is currently (April 2011) the only ORM that runs on Windows Phone for local data access using SQLite in isolated storage

Find the index of a dict within a list, by matching the dict's value

lst = [{'id':'1234','name':'Jason'}, {'id':'2345','name':'Tom'}, {'id':'3456','name':'Art'}]

tom_index = next((index for (index, d) in enumerate(lst) if d["name"] == "Tom"), None)
# 1

If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:

def build_dict(seq, key):
    return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))

info_by_name = build_dict(lst, key="name")
tom_info = info_by_name.get("Tom")
# {'index': 1, 'id': '2345', 'name': 'Tom'}

Converting an integer to a string in PHP

I would say it depends on the context. strval() or the casting operator (string) could be used. However, in most cases PHP will decide what's good for you if, for example, you use it with echo or printf...

One small note: die() needs a string and won't show any int :)

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

Checking if a variable is not nil and not zero in ruby

You could initialize discount to 0 as long as your code is guaranteed not to try and use it before it is initialized. That would remove one check I suppose, I can't think of anything else.

jQuery UI Slider (setting programmatically)

Finally below works for me

$("#priceSlider").slider('option',{min: 5, max: 20,value:[6,19]}); $("#priceSlider").slider("refresh");

PHP: Get the key from an array in a foreach loop

Use foreach with key and value.

Example:

foreach($samplearr as $key => $val) {
     print "<tr><td>" 
         . $key 
         . "</td><td>" 
         . $val['value1'] 
         . "</td><td>" 
         . $val['value2'] 
         . "</td></tr>";
}

How do I get the current year using SQL on Oracle?

Yet another option would be:

SELECT * FROM mytable
 WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');

Adding 30 minutes to time formatted as H:i in PHP

Your current solution does not work because $time is a string - it needs to be a Unix timestamp. You can do this instead:

$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );

jQuery - find table row containing table cell containing specific text

   <input type="text" id="text" name="search">
<table id="table_data">
        <tr class="listR"><td>PHP</td></tr>
        <tr class="listR"><td>MySql</td></tr>
        <tr class="listR"><td>AJAX</td></tr>
        <tr class="listR"><td>jQuery</td></tr>
        <tr class="listR"><td>JavaScript</td></tr>
        <tr class="listR"><td>HTML</td></tr>
        <tr class="listR"><td>CSS</td></tr>
        <tr class="listR"><td>CSS3</td></tr>
</table>

$("#textbox").on('keyup',function(){
        var f = $(this).val();
      $("#table_data tr.listR").each(function(){
            if ($(this).text().search(new RegExp(f, "i")) < 0) {
                $(this).fadeOut();
             } else {
                 $(this).show();
            }
        });
    });

Demo You can perform by search() method with use RegExp matching text

How to remove focus from single editText

Just include this line

android:selectAllOnFocus="false"

in the XML segment corresponding to the EditText layout.

Select 50 items from list at random to write to file

I think random.choice() is a better option.

import numpy as np

mylist = [13,23,14,52,6,23]

np.random.choice(mylist, 3, replace=False)

the function returns an array of 3 randomly chosen values from the list

Is it possible to auto-format your code in Dreamweaver?

Auto formatting can be done by

  • Select View > Code View Options
  • Click the View Options button enter image description here in the toolbar at the top of Code view or the Code inspector.

Auto Indent Makes your code indent automatically when you press Enter while writing code.

source

Logical operators ("and", "or") in DOS batch

De Morgan's laws allow us to convert disjunctions ("OR") into logical equivalents using only conjunctions ("AND") and negations ("NOT"). This means we can chain disjunctions ("OR") on to one line.

This means if name is "Yakko" or "Wakko" or "Dot", then echo "Warner brother or sister".

set warner=true
if not "%name%"=="Yakko" if not "%name%"=="Wakko" if not "%name%"=="Dot" set warner=false
if "%warner%"=="true" echo Warner brother or sister

This is another version of paxdiablo's "OR" example, but the conditions are chained on to one line. (Note that the opposite of leq is gtr, and the opposite of geq is lss.)

set res=true
if %hour% gtr 6 if %hour% lss 22 set res=false
if "%res%"=="true" set state=asleep

Vertical divider CSS

<div class="headerdivider"></div>

and

.headerdivider {
    border-left: 1px solid #38546d;
    background: #16222c;
    width: 1px;
    height: 80px;
    position: absolute;
    right: 250px;
    top: 10px;
}

DataTables: Cannot read property 'length' of undefined

While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.

How do I delete from multiple tables using INNER JOIN in SQL server

$sql="DELETE FROM basic_tbl,education_tbl, personal_tbl ,address_tbl,department_tbl USING basic_tbl,education_tbl, personal_tbl ,address_tbl,department_tbl WHERE b_id=e_id=p_id=a_id=d_id='".$id."' "; $rs=mysqli_query($con,$sql);

Is there a way to use shell_exec without waiting for the command to complete?

How about adding.

"> /dev/null 2>/dev/null &"

shell_exec('php measurePerformance.php 47 844 [email protected] > /dev/null 2>/dev/null &');

Note this also gets rid of the stdio and stderr.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

you do not need to clean all files in dir C:\Users\ ~User Name~ \.gradle\wrapper\dists. and download all of them again

instead you can just delete the folder of gradle version you failed to download. In my case it was gradle-4.4-all so i just deleted that folder and android studio re downloaded gradle-4.4-all for me

In case you don't know version you was downloading:

Just go to help menu > show logs in explorer

their you will find idea.log open it and search for

Could not install Gradle distribution from 'https://services.gradle.org/distribution`

once you find it you will find gradle version you failed to download

How can I parse a local JSON file from assets folder into a ListView?

Method to read JSON file from Assets folder and return as a string object.

public static String getAssetJsonData(Context context) {
            String json = null;
            try {
                InputStream is = context.getAssets().open("myJson.json");
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                json = new String(buffer, "UTF-8");
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }

            Log.e("data", json);
            return json;

        }

Now for parsing data in your activity:-

String data = getAssetJsonData(getApplicationContext());
        Type type = new TypeToken<Your Data model>() {
        }.getType();
  <Your Data model> modelObject = new Gson().fromJson(data, type);

Full-screen responsive background image

Try this:

<img src="images/background.jpg" 

style="width:100%;height:100%;position:absolute;top:0;left:0;z-index:-5000;">

http://thewebthought.blogspot.com/2010/10/css-making-background-image-fit-any.html

Extract a part of the filepath (a directory) in Python

import os

directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'

parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'

This should also do the trick.

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Go to Preferences -> Accounts, remove your account and add it again. Then try uploading again and wait a few minutes.

Do C# Timers elapse on a separate thread?

For System.Timers.Timer:

See Brian Gideon's answer below

For System.Threading.Timer:

MSDN Documentation on Timers states:

The System.Threading.Timer class makes callbacks on a ThreadPool thread and does not use the event model at all.

So indeed the timer elapses on a different thread.

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

'tsc command not found' in compiling typescript

I had this same problem on Ubuntu 19.10 LTS.

To solve this I ran the following command:

$ sudo apt install node-typescript

After that, I was able to use tsc.

Get pixel color from canvas, on mousemove

Here's a complete, self-contained example. First, use the following HTML:

<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>

Then put some squares on the canvas with random background colors:

var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);

And print each color on mouseover:

$('#example').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "<br>" + hex);
});

The code above assumes the presence of jQuery and the following utility functions:

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function randomInt(max) {
  return Math.floor(Math.random() * max);
}

function randomColor() {
    return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}

See it in action here:

_x000D_
_x000D_
// set up some sample squares with random colors
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = randomColor();
context.fillRect(0, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(55, 0, 50, 50);
context.fillStyle = randomColor();
context.fillRect(110, 0, 50, 50);

$('#example').mousemove(function(e) {
    var pos = findPos(this);
    var x = e.pageX - pos.x;
    var y = e.pageY - pos.y;
    var coord = "x=" + x + ", y=" + y;
    var c = this.getContext('2d');
    var p = c.getImageData(x, y, 1, 1).data; 
    var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
    $('#status').html(coord + "<br>" + hex);
});

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function rgbToHex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

function randomInt(max) {
  return Math.floor(Math.random() * max);
}

function randomColor() {
    return `rgb(${randomInt(256)}, ${randomInt(256)}, ${randomInt(256)})`
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>

    
_x000D_
_x000D_
_x000D_

How do I shrink my SQL Server Database?

Not sure how practical this would be, and depending on the size of the database, number of tables and other complexities, but I:

  1. defrag the physical drive
  2. create a new database according to my requirements, space, percentage growth, etc
  3. use the simple ssms task to import all tables from the old db to the new db
  4. script out the indexes for all tables on the old database, and then recreate the indexes on the new database. expand as needed for foreign keys etc.
  5. rename databases as needed, confirm successful, delete old

VB.NET: Clear DataGridView

just write this

DataGridView1.DataSource = ""

jQuery check if Cookie exists, if not create it

I was having alot of trouble with this because I was using:

if($.cookie('token') === null || $.cookie('token') === "")
{
      //no cookie
}
else
{
     //have cookie
}

The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.

if($.cookie('token') === null || $.cookie('token') === "" 
    || $.(cookie('token') === "null" || $.cookie('token') === undefined)
{
      //no cookie
}
else
{
     //have cookie
}

How to prevent buttons from submitting forms

Suppose your HTML form has id="form_id"

<form id="form_id">
<!--your HTML code-->
</form>

Add this jQuery snippet to your code to see result,

$("#form_id").submit(function(){
  return false;
});

How to resize JLabel ImageIcon?

Try this :

ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
imageIcon = new ImageIcon(newimg);  // transform it back

(found it here)

Why would an Enum implement an Interface?

Enums don't just have to represent passive sets (e.g. colours). They can represent more complex objects with functionality, and so you're then likely to want to add further functionality to these - e.g. you may have interfaces such as Printable, Reportable etc. and components that support these.

How can I get screen resolution in java?

These three functions return the screen size in Java. This code accounts for multi-monitor setups and task bars. The included functions are: getScreenInsets(), getScreenWorkingArea(), and getScreenTotalArea().

Code:

/**
 * getScreenInsets, This returns the insets of the screen, which are defined by any task bars
 * that have been set up by the user. This function accounts for multi-monitor setups. If a
 * window is supplied, then the the monitor that contains the window will be used. If a window
 * is not supplied, then the primary monitor will be used.
 */
static public Insets getScreenInsets(Window windowOrNull) {
    Insets insets;
    if (windowOrNull == null) {
        insets = Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration());
    } else {
        insets = windowOrNull.getToolkit().getScreenInsets(
                windowOrNull.getGraphicsConfiguration());
    }
    return insets;
}

/**
 * getScreenWorkingArea, This returns the working area of the screen. (The working area excludes
 * any task bars.) This function accounts for multi-monitor setups. If a window is supplied,
 * then the the monitor that contains the window will be used. If a window is not supplied, then
 * the primary monitor will be used.
 */
static public Rectangle getScreenWorkingArea(Window windowOrNull) {
    Insets insets;
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        insets = Toolkit.getDefaultToolkit().getScreenInsets(ge.getDefaultScreenDevice()
                .getDefaultConfiguration());
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        insets = windowOrNull.getToolkit().getScreenInsets(gc);
        bounds = gc.getBounds();
    }
    bounds.x += insets.left;
    bounds.y += insets.top;
    bounds.width -= (insets.left + insets.right);
    bounds.height -= (insets.top + insets.bottom);
    return bounds;
}

/**
 * getScreenTotalArea, This returns the total area of the screen. (The total area includes any
 * task bars.) This function accounts for multi-monitor setups. If a window is supplied, then
 * the the monitor that contains the window will be used. If a window is not supplied, then the
 * primary monitor will be used.
 */
static public Rectangle getScreenTotalArea(Window windowOrNull) {
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        bounds = gc.getBounds();
    }
    return bounds;
}

Can you force Visual Studio to always run as an Administrator in Windows 8?

If you using Total Commander as I do, you should do the same for Total Commander to be run as admin always. Then you will be able to open sql file on double click in same SQL Server management instance, or to open any Visual Studio file on double click and not have multiple instances open.

This Troubleshoot program adds registry value to HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers for any program, so if you like to write it directly you can.

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

String Array object in Java

First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.

However, if you really want to use that Getter and Setter, change the public modifier to private instead.

Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
----------Shadowing sample----------
You have the following class:

public String name;

public Person(String name){
    this.name = name; // This is Shadowing
}

In your main method for example, you instantiate the Person class as follow:
Person person = new Person("theolc");

Variable name will be equal to "theolc".
----------End of shadowing----------

Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.

public class Athlete {

public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};

public Athlete() {

}

In your main method, you could do this.

public static void main(String[] args) {
       Athlete art = new Athlete();   

       System.out.println(art.name[0]);
       System.out.println(art.country[0]);
    }
}

How do shift operators work in Java?

I believe this might Help:

    System.out.println(Integer.toBinaryString(2 << 0));
    System.out.println(Integer.toBinaryString(2 << 1));
    System.out.println(Integer.toBinaryString(2 << 2));
    System.out.println(Integer.toBinaryString(2 << 3));
    System.out.println(Integer.toBinaryString(2 << 4));
    System.out.println(Integer.toBinaryString(2 << 5));

Result

    10
    100
    1000
    10000
    100000
    1000000

Edited:

Must Read This (how-do-the-bitwise-shift-operators-work)

How to get query parameters from URL in Angular 5?

Simple Solution

 // in routing file
       {
            path: 'checkout/:cartId/:addressId',
            loadChildren: () => import('./pages/checkout/checkout.module').then(m => m.CheckoutPageModule)
          },

    // in Component file

            import { Router, ActivatedRoute } from '@angular/router';

                 constructor(
                      private _Router: ActivatedRoute
                  ) { }

                  ngOnInit() {
                    this.cartId = this._Router.snapshot.params.cartId;
                    this.addressId = this._Router.snapshot.params.addressId;
                    console.log(this.addressId, "addressId")
                    console.log(this.cartId, "cartId")
                  }

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

For me I did enter a invalid url like : orcl only instead of jdbc:oracle:thin:@//localhost:1521/orcl

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

JSHint and jQuery: '$' is not defined

You probably want to do the following,

const $ = window.$

to avoid it throwing linting error.

Detect key input in Python

use the builtin: (no need for tkinter)

s = input('->>')
print(s) # what you just typed); now use if's 

How to get multiline input from user

input(prompt) is basically equivalent to

def input(prompt):
    print(prompt, end='', file=sys.stderr)
    return sys.stdin.readline()

You can read directly from sys.stdin if you like.

lines = sys.stdin.readlines()

lines = [line for line in sys.stdin]

five_lines = list(itertools.islice(sys.stdin, 5))

The first two require that the input end somehow, either by reaching the end of a file or by the user typing Control-D (or Control-Z in Windows) to signal the end. The last one will return after five lines have been read, whether from a file or from the terminal/keyboard.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

How to store token in Local or Session Storage in Angular 2?

Save to local storage

localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));

Load from local storage

var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; // your token

For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial

Android Studio - Device is connected but 'offline'

Download and Install your device driver manually through visiting manufacturer website like :Samsung,micromax,intex etc.

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

In the first place consider the Small grid, see: http://getbootstrap.com/css/#grid-options. A max container width of 750 px will maybe to small for you (also read: Why does Bootstrap 3 force the container width to certain sizes?)

When using the Small grid use media queries to set the max-container width:

@media (min-width: 768px) { .container { max-width: 750px; } }

Second also read this question: Bootstrap 3 - 940px width grid?, possible duplicate?

12 x 60 = 720px for the columns and 11 x 20 = 220px

there will also a gutter of 20px on both sides of the grid so 220 + 720 + 40 makes 980px

there is 'no' @ColumnWidth

You colums width will be calculated dynamically based on your settings in variables.less. you could set @grid-columns and @grid-gutter-width. The width of a column will be set as a percentage via grid.less in mixins.less:

.calc-grid(@index, @class, @type) when (@type = width) {
  .col-@{class}-@{index} {
    width: percentage((@index / @grid-columns));
  }
}

update Set @grid-gutter-width to 20px;, @container-desktop: 940px;, @container-large-desktop: @container-desktop and recompile bootstrap.

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

What I can do to fix this (other than installing a real SSL certificate).

You can't.

On an https webpage you can only make AJAX request to https webpage (With a certificate trusted by the browser, if you use a self-signed one, it will not work for your visitors)

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

new Runnable() but no new thread?

Best and easy way is just pass argument and create instance and call thread method

Call thread using create a thread object and send a runnable class object with parameter or without parameter and start method of thread object.

In my condition I am sending parameter and I will use in run method.

new Thread(new FCMThreadController("2", null, "3", "1")).start();

OR

new Thread(new FCMThreadController()).start();

public class FCMThreadController implements Runnable {
private String type;
private List<UserDeviceModel> devices;
private String message;
private String id;


    public FCMThreadController(String type, List<UserDeviceModel> devices, String message, String id) {

        this.type = type;
        this.devices = devices;
        this.message = message;
        this.id = id;
    }



    public FCMThreadController( ) {

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }



}

JAXB: How to ignore namespace during unmarshalling XML document?

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

  • Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
  • Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}

Refresh certain row of UITableView based on Int in Swift

You can create an NSIndexPath using the row and section number then reload it like so:

let indexPath = NSIndexPath(forRow: rowNumber, inSection: 0)
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)

In this example, I've assumed that your table only has one section (i.e. 0) but you may change that value accordingly.

Update for Swift 3.0:

let indexPath = IndexPath(item: rowNumber, section: 0)
tableView.reloadRows(at: [indexPath], with: .top)

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

How can foreign key constraints be temporarily disabled using T-SQL?

One script to rule them all: this combines truncate and delete commands with sp_MSforeachtable so that you can avoid dropping and recreating constraints - just specify the tables that need to be deleted rather than truncated and for my purposes I have included an extra schema filter for good measure (tested in 2008r2)

declare @schema nvarchar(max) = 'and Schema_Id=Schema_id(''Value'')'
declare @deletiontables nvarchar(max) = '(''TableA'',''TableB'')'
declare @truncateclause nvarchar(max) = @schema + ' and o.Name not in ' +  + @deletiontables;
declare @deleteclause nvarchar(max) = @schema + ' and o.Name in ' + @deletiontables;        

exec sp_MSforeachtable 'alter table ? nocheck constraint all', @whereand=@schema
exec sp_MSforeachtable 'truncate table ?', @whereand=@truncateclause
exec sp_MSforeachtable 'delete from ?', @whereand=@deleteclause
exec sp_MSforeachtable 'alter table ? with check check constraint all', @whereand=@schema

Should I use alias or alias_method?

alias_method new_method, old_method

old_method will be declared in a class or module which is being inherited now to our class where new_method will be used.

these can be variable or method both.

Suppose Class_1 has old_method, and Class_2 and Class_3 both of them inherit Class_1.

If, initialization of Class_2 and Class_3 is done in Class_1 then both can have different name in Class_2 and Class_3 and its usage.

MySQL duplicate entry error even though there is no duplicate entry

Your code and schema are OK. You probably trying on previous version of table.

http://sqlfiddle.com/#!2/9dc64/1/0

Your table even has no UNIQUE, so that error is impossible on that table.

Backup data from that table, drop it and re-create.

Maybe you tried to run that CREATE TABLE IF NOT EXIST. It was not created, you have old version, but there was no error because of IF NOT EXIST.

You may run SQL like this to see current table structure:

DESCRIBE my_table;

Edit - added later:

Try to run this:

DROP TABLE `my_table`; --make backup - it deletes table

CREATE TABLE `my_table` (
  `number` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `money` int(11) NOT NULL,
  PRIMARY KEY (`number`,`name`),
  UNIQUE (`number`, `name`) --added unique on 2 rows
) ENGINE=MyISAM;

How do you access the matched groups in a JavaScript regular expression?

I you are like me and wish regex would return an Object like this:

{
    match: '...',
    matchAtIndex: 0,
    capturedGroups: [ '...', '...' ]
}

then snip the function from below

_x000D_
_x000D_
/**_x000D_
 * @param {string | number} input_x000D_
 *          The input string to match_x000D_
 * @param {regex | string}  expression_x000D_
 *          Regular expression _x000D_
 * @param {string} flags_x000D_
 *          Optional Flags_x000D_
 * _x000D_
 * @returns {array}_x000D_
 * [{_x000D_
    match: '...',_x000D_
    matchAtIndex: 0,_x000D_
    capturedGroups: [ '...', '...' ]_x000D_
  }]     _x000D_
 */_x000D_
function regexMatch(input, expression, flags = "g") {_x000D_
  let regex = expression instanceof RegExp ? expression : new RegExp(expression, flags)_x000D_
  let matches = input.matchAll(regex)_x000D_
  matches = [...matches]_x000D_
  return matches.map(item => {_x000D_
    return {_x000D_
      match: item[0],_x000D_
      matchAtIndex: item.index,_x000D_
      capturedGroups: item.length > 1 ? item.slice(1) : undefined_x000D_
    }_x000D_
  })_x000D_
}_x000D_
_x000D_
let input = "key1:value1, key2:value2 "_x000D_
let regex = /(\w+):(\w+)/g_x000D_
_x000D_
let matches = regexMatch(input, regex)_x000D_
_x000D_
console.log(matches)
_x000D_
_x000D_
_x000D_

Execute an action when an item on the combobox is selected

The simple solution would be to use a ItemListener. When the state changes, you would simply check the currently selected item and set the text accordingly

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

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

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new String[]{"Item 1", "Item 2"});
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Object item = cb.getSelectedItem();
                    if ("Item 1".equals(item)) {
                        field.setText("20");
                    } else if ("Item 2".equals(item)) {
                        field.setText("30");
                    }
                }
            });
        }

    }

}

A better solution would be to create a custom object that represents the value to be displayed and the value associated with it...

Updated

Now I no longer have a 10 month chewing on my ankles, I updated the example to use a ListCellRenderer which is a more correct approach then been lazy and overriding toString

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

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

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new Item[]{
                new Item("Item 1", "20"), 
                new Item("Item 2", "30")});
            cb.setRenderer(new ItemCelLRenderer());
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Item item = (Item)cb.getSelectedItem();
                    field.setText(item.getValue());
                }
            });
        }

    }

    public class Item {
        private String value;
        private String text;

        public Item(String text, String value) {
            this.text = text;
            this.value = value;
        }

        public String getText() {
            return text;
        }

        public String getValue() {
            return value;
        }

    }

    public class ItemCelLRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
            if (value instanceof Item) {
                setText(((Item)value).getText());
            }
            return this;
        }

    }

}

How to randomize (shuffle) a JavaScript array?

This variation of Fisher-Yates is slightly more efficient because it avoids swapping an element with itself:

function shuffle(array) {
  var elementsRemaining = array.length, temp, randomIndex;
  while (elementsRemaining > 1) {
    randomIndex = Math.floor(Math.random() * elementsRemaining--);
    if (randomIndex != elementsRemaining) {
      temp = array[elementsRemaining];
      array[elementsRemaining] = array[randomIndex];
      array[randomIndex] = temp;
    }
  }
  return array;
}

How to programmatically move, copy and delete files and directories on SD?

To move a file this api can be used but you need atleat 26 as api level -

move file

But if you want to move directory no support is there so this native code can be used

    import org.apache.commons.io.FileUtils;

    import java.io.IOException;
    import java.io.File;

    public class FileModule {

    public void moveDirectory(String src, String des) {
    File srcDir = new File(src);
    File destDir = new File(des);
     try {
        FileUtils.moveDirectory(srcDir,destDir);
    } catch (Exception e) {
      Log.e("Exception" , e.toString());
      }
    }

    public void deleteDirectory(String dir) {
      File delDir = new File(dir);
      try {
        FileUtils.deleteDirectory(delDir);
       } catch (IOException e) {
      Log.e("Exception" , e.toString());
      }
     }
    }

What is the keyguard in Android?

The lock screen works without keyguard i have tested it. The home button stops working and you can't get to task manager by holding the home key. I wish they didn't develop a new process when it used to be built into system ui or whatever. I don't see the need for the change and extra process

How do I view cookies in Internet Explorer 11 using Developer Tools

I think I found what you are looking for since I was also looking for it.

You have to follow Pawel's steps and then go to the key that is "Cookie". This will open a submenu with all the cookies and it specifies their name, value, domain, etc...

enter image description here

Respectively the values are: Key, Value, Expiration Date, Domain, Path.

This shows all the keys for this domain.

So again to get there:

  1. Go to Network.
  2. Capture Traffic, green triangle.
  3. Go to Details.
  4. Go to the "Cookie" key that has a gibberish value. (_utmc=xxxxx;something=ajksdhfa) etc...

php: catch exception and continue execution, is it possible?

For PHP 8+ we can omit the variable name for a caught exception.

catch

As of PHP 8.0.0, the variable name for a caught exception is optional. If not specified, the catch block will still execute but will not have access to the thrown object.

And thus we can do it like this:

try {
  throw new Exception("An error");
}
catch (Exception) {}

Woocommerce get products

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

Inserting image into IPython notebook markdown

minrk's answer is right.

However, I found that the images appeared broken in Print View (on my Windows machine running the Anaconda distribution of IPython version 0.13.2 in a Chrome browser)

The workaround for this was to use <img src="../files/image.png"> instead.

This made the image appear correctly in both Print View and the normal iPython editing view.

UPDATE: as of my upgrade to iPython v1.1.0 there is no more need for this workaround since the print view no longer exists. In fact, you must avoid this workaround since it prevents the nbconvert tool from finding the files.

How to execute a function when page has fully loaded?

In modern browsers with modern javascript (>= 2015) you can add type="module" to your script tag, and everything inside that script will execute after whole page loads. e.g:

<script type="module">
  alert("runs after") // Whole page loads before this line execute
</script>
<script>
  alert("runs before")
</script>

also older browsers will understand nomodule attribute. Something like this:

<script nomodule>
  alert("tuns after")
</script>

For more information you can visit javascript.info.

How can I delete derived data in Xcode 8?

It may differ between versions of xcodes. Best approach is to go xcode preference page and from tab "Locations", directly open "Derived Data" directory.

How to lookup JNDI resources on WebLogic?

You should be able to simply do this:

Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

If you are looking it up from a remote destination you need to use the WL initial context factory like this:

Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);

InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

weblogic.jndi.WLInitialContextFactory

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

The answer is here: http://sysadminsjourney.com/content/2010/02/01/apache-modproxy-error-13permission-denied-error-rhel/

Which is a link to a blog that explains:

SELinux on RHEL/CentOS by default ships so that httpd processes cannot initiate outbound connections, which is just what mod_proxy attempts to do.

If this is the problem, it can be solved by running:

 /usr/sbin/setsebool -P httpd_can_network_connect 1

And for a more definitive source of information, see https://wiki.apache.org/httpd/13PermissionDenied

Launch Bootstrap Modal on page load

In order to avoid bootstrap being overruled and loosing it´s funcionality, simply create a regular launch button, provide it with an Id, and 'click it' using jquery, like so: The launch button:

<button type="button" id="btnAnouncement" class="btn btn-primary" data-toggle="modal" data-target="#modalAnouncement">
  See what´s new!
</button>

The jQuery trigger:

$(document).ready(function () {
  $('#btnAnouncement').click();
)}

Hope it helps. Cheers!

What value could I insert into a bit type column?

Your issue is in PHPMyAdmin itself. Some versions do not display the value of bit columns, even though you did set it correctly.

Range with step of type float

The problem with floating point is that you may not get the same number of items as you expected, due to inaccuracy. This can be a real problem if you are playing with polynomials where the exact number of items is quite important.

What you really want is an arithmetic progression; the following code will work quite happily for int, float and complex ... and strings, and lists ...

def arithmetic_progression(start, step, length):
    for i in xrange(length):
        yield start + i * step

Note that this code stands a better chance of your last value being within a bull's roar of the expected value than any alternative which maintains a running total.

>>> 10000 * 0.0001, sum(0.0001 for i in xrange(10000))
(1.0, 0.9999999999999062)
>>> 10000 * (1/3.), sum(1/3. for i in xrange(10000))
(3333.333333333333, 3333.3333333337314)

Correction: here's a competetive running-total gadget:

def kahan_range(start, stop, step):
    assert step > 0.0
    total = start
    compo = 0.0
    while total < stop:
        yield total
        y = step - compo
        temp = total + y
        compo = (temp - total) - y
        total = temp

>>> list(kahan_range(0, 1, 0.0001))[-1]
0.9999
>>> list(kahan_range(0, 3333.3334, 1/3.))[-1]
3333.333333333333
>>>

How to detect scroll position of page using jQuery

You can extract the scroll position using jQuery's .scrollTop() method

$(window).scroll(function (event) {
    var scroll = $(window).scrollTop();
    // Do something
});

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Move div to new line

What about something like this.

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
        <div class="movie_item_content_year">year</div>
        <div class="movie_item_content_title">title</div>
        <div class="movie_item_content_plot">plot</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

You don't have to float both movie_item_poster AND movie_item_content. Just float one of them...

#movie_item {
    position: relative;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
}

.movie_item_content {
    position: relative;
}

.movie_item_content_title {
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

Here it is as a JSFiddle.

How to get Chrome to allow mixed content?

Chrome 46 and newer should be showing mixed content without any warning, just without the green lock in address bar.

Source: Simplifying the Page Security Icon in Chrome at Google Online Security Blog.

Get the latest date from grouped MySQL data

Using max(date) didn't solve my problem as there is no assurance that other columns will be from the same row as the max(date) is. Instead of that this one solved my problem and sorted group by in a correct order and values of other columns are from the same row as the max date is:

SELECT model, date 
FROM (SELECT * FROM doc ORDER BY date DESC) as sortedTable
GROUP BY model

What is the difference between MVC and MVVM?

mvc is server-side and mvvm is client-side(browser) in web development.

most of the time javascript is used for mvvm in browser. there are many server side technologies for mvc.

How do I clear a search box with an 'x' in bootstrap 3?

Super-simple HTML 5 Solution:

_x000D_
_x000D_
<input type="search" placeholder="Search..." />
_x000D_
_x000D_
_x000D_

Source: HTML 5 Tutorial - Input Type: Search

That works in at least Chrome 8, Edge 14, IE 10, and Safari 5 and does not require Bootstrap or any other library. (Unfortunately, it seems Firefox does not support the search clear button yet.)

After typing in the search box, an 'x' will appear which can be clicked to clear the text. This will still work as an ordinary edit box (without the 'x' button) in other browsers, such as Firefox, so Firefox users could instead select the text and press delete, or...

If you really need this nice-to-have feature supported in Firefox, then you could implement one of the other solutions posted here as a polyfill for input[type=search] elements. A polyfill is code that automatically adds a standard browser feature when the user's browser doesn't support the feature. Over time, the hope is that you'd be able to remove polyfills as browsers implement the respective features. And in any case, a polyfill implementation can help to keep the HTML code cleaner.

By the way, other HTML 5 input types (such as "date", "number", "email", etc.) will also degrade gracefully to a plain edit box. Some browsers might give you a fancy date picker, a spinner control with up/down buttons, or (on mobile phones) a special keyboard that includes the '@' sign and a '.com' button, but to my knowledge, all browsers will at least show a plain text box for any unrecognized input type.


Bootstrap 3 & HTML 5 Solution

Bootstrap 3 resets a lot of CSS and breaks the HTML 5 search cancel button. After the Bootstrap 3 CSS has been loaded, you can restore the search cancel button with the CSS used in the following example:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<style>_x000D_
  input[type="search"]::-webkit-search-cancel-button {_x000D_
    -webkit-appearance: searchfield-cancel-button;_x000D_
  }_x000D_
</style>_x000D_
<div class="form-inline">_x000D_
  <input type="search" placeholder="Search..." class="form-control" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Source: HTML 5 Search Input Does Not Work with Bootstrap

I have tested that this solution works in the latest versions of Chrome, Edge, and Internet Explorer. I am not able to test in Safari. Unfortunately, the 'x' button to clear the search does not appear in Firefox, but as above, a polyfill could be implemented for browsers that don't support this feature natively (i.e. Firefox).

Parse XLSX with Node and create json

here's angular 5 method version of this with unminified syntax for those who struggling with that y, z, tt in accepted answer. usage: parseXlsx().subscribe((data)=> {...})

parseXlsx() {
    let self = this;
    return Observable.create(observer => {
        this.http.get('./assets/input.xlsx', { responseType: 'arraybuffer' }).subscribe((data: ArrayBuffer) => {
            const XLSX = require('xlsx');
            let file = new Uint8Array(data);
            let workbook = XLSX.read(file, { type: 'array' });
            let sheetNamesList = workbook.SheetNames;

            let allLists = {};
            sheetNamesList.forEach(function (sheetName) {
                let worksheet = workbook.Sheets[sheetName];
                let currentWorksheetHeaders: object = {};
                let data: Array<any> = [];
                for (let cellName in worksheet) {//cellNames example: !ref,!margins,A1,B1,C1

                    //skipping serviceCells !margins,!ref
                    if (cellName[0] === '!') {
                        continue
                    };

                    //parse colName, rowNumber, and getting cellValue
                    let numberPosition = self.getCellNumberPosition(cellName);
                    let colName = cellName.substring(0, numberPosition);
                    let rowNumber = parseInt(cellName.substring(numberPosition));
                    let cellValue = worksheet[cellName].w;// .w is XLSX property of parsed worksheet

                    //treating '-' cells as empty on Spot Indices worksheet
                    if (cellValue.trim() == "-") {
                        continue;
                    }

                    //storing header column names
                    if (rowNumber == 1 && cellValue) {
                        currentWorksheetHeaders[colName] = typeof (cellValue) == "string" ? cellValue.toCamelCase() : cellValue;
                        continue;
                    }

                    //creating empty object placeholder to store current row
                    if (!data[rowNumber]) {
                        data[rowNumber] = {}
                    };

                    //if header is date - for spot indices headers are dates
                    data[rowNumber][currentWorksheetHeaders[colName]] = cellValue;

                }

                //dropping first two empty rows
                data.shift();
                data.shift();
                allLists[sheetName.toCamelCase()] = data;
            });

            this.parsed = allLists;

            observer.next(allLists);
            observer.complete();
        })
    });
}

Where is the user's Subversion config file stored on the major operating systems?

Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

Go to System preferences -> MySql and check the state of your MySql instance.

How to get substring of NSString?

Option 1:

NSString *haystack = @"value:hello World:value";
NSString *haystackPrefix = @"value:";
NSString *haystackSuffix = @":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
                                  haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle); // -> "hello World"

Option 2:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];

This one might be a bit over the top for your rather trivial case though.

Option 3:

NSString *needle = [haystack componentsSeparatedByString:@":"][1];

This one creates three temporary strings and an array while splitting.


All snippets assume that what's searched for is actually contained in the string.

Convert char to int in C#

Has anyone considered using int.Parse() and int.TryParse() like this

int bar = int.Parse(foo.ToString());

Even better like this

int bar;
if (!int.TryParse(foo.ToString(), out bar))
{
    //Do something to correct the problem
}

It's a lot safer and less error prone

Dynamically allocating an array of objects

Why not have a setSize method.

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    arrayOfAs[i].SetSize(3);
}

I like the "copy" but in this case the default constructor isn't really doing anything. The SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that.
OR
The SetSize could delete the original m_array.

void SetSize(unsigned int p_newSize)
{
    //I don't care if it's null because delete is smart enough to deal with that.
    delete myArray;
    myArray = new int[p_newSize];
    ASSERT(myArray);
}

`getchar()` gives the same output as the input string

In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

How to add custom html attributes in JSX

I ran into this problem a lot when attempting to use SVG with react.

I ended up using quite a dirty fix, but it's useful to know this option existed. Below I allow the use of the vector-effect attribute on SVG elements.

import SVGDOMPropertyConfig from 'react/lib/SVGDOMPropertyConfig.js';
import DOMProperty from 'react/lib/DOMProperty.js';

SVGDOMPropertyConfig.Properties.vectorEffect = DOMProperty.injection.MUST_USE_ATTRIBUTE;
SVGDOMPropertyConfig.DOMAttributeNames.vectorEffect = 'vector-effect';

As long as this is included/imported before you start using react, it should work.

Interface defining a constructor signature?

Beginning with C# 8.0, an interface member may declare a body. This is called a default implementation. Members with bodies permit the interface to provide a "default" implementation for classes and structs that don't provide an overriding implementation. In addition, beginning with C# 8.0, an interface may include:

Constants Operators Static constructor. Nested types Static fields, methods, properties, indexers, and events Member declarations using the explicit interface implementation syntax. Explicit access modifiers (the default access is public).

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Make columns of equal width in <table>

Use following property same as table and its fully dynamic:

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed; /* optional, for equal spacing */_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid pink;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz klxjgkldjklg </li>_x000D_
  <li>baz</li>_x000D_
  <li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

May be its solve your issue.

psql: FATAL: role "postgres" does not exist

If you installed postgres from brew, run this in your terminal :

/usr/local/opt/postgres/bin/createuser -s postgres

Apache is downloading php files instead of displaying them

this solved the problem for me (I have php7 installed):

sudo apt-get install libapache2-mod-php7.0

sudo service apache2 restart

Powershell Execute remote exe with command line arguments on remote computer

$sb = ScriptBlock::Create("$command")
Invoke-Command -ScriptBlock $sb

This should work and avoid misleading the beginners.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

This has happened to me after I "updated" into 5.0 SDK and wanted to create a new application with support library

In both Projects (project.properties file) in the one you want to use support library and the support library itself it has to be set the same target

e.g. for my case it worked

  1. In project android-support-v7-appcompat Change project.properties into target=android-21
  2. Cleanandroid-support-v7-appcompat In my project (where I desire support library)
  3. In my project, Change project.properties into target=android-21 and android.library.reference.1=../android-support-v7-appcompat (or add support library in project properties)
  4. Clean the project

Transport endpoint is not connected

This typically is caused by the mount directory being left mounted due to a crash of your filesystem. Go to the parent directory of the mount point and enter fusermount -u YOUR_MNT_DIR.

If this doesn't do the trick, do sudo umount -l YOUR_MNT_DIR.

How do I convert Word files to PDF programmatically?

PDFCreator has a COM component, callable from .NET or VBScript (samples included in the download).

But, it seems to me that a printer is just what you need - just mix that with Word's automation, and you should be good to go.

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

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

Multiple submit buttons in the same form calling different Servlets

You may need to write a javascript for each button submit. Instead of defining action in form definition, set those values in javascript. Something like below.

function callButton1(form, yourServ)
{
form.action = yourServ;
form.submit();
});

SMTP connect() failed PHPmailer - PHP

I fixed it ...

https://github.com/PHPMailer/PHPMailer/tree/5.2-stable

_x000D_
_x000D_
<?php_x000D_
require 'PHPMailerAutoload.php';_x000D_
_x000D_
$mail = new PHPMailer;_x000D_
_x000D_
//$mail->SMTPDebug = 3;                               // Enable verbose debug output_x000D_
_x000D_
$mail->isSMTP();                                      // Set mailer to use SMTP_x000D_
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers_x000D_
$mail->SMTPAuth = true;                               // Enable SMTP authentication_x000D_
$mail->Username = '[email protected]';                 // SMTP username_x000D_
$mail->Password = 'pass';                           // SMTP password_x000D_
//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted_x000D_
$mail->Port = 25;                                    // TCP port to connect to_x000D_
_x000D_
$mail->setFrom('[email protected]', 'Mailer');_x000D_
$mail->addAddress('[email protected]', 'User');     // Add a recipient_x000D_
_x000D_
$mail->isHTML(true);                                  // Set email format to HTML_x000D_
_x000D_
$mail->Subject = 'Here is the subject';_x000D_
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';_x000D_
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';_x000D_
_x000D_
if(!$mail->send()) {_x000D_
    echo 'Message could not be sent.';_x000D_
    echo 'Mailer Error: ' . $mail->ErrorInfo;_x000D_
} else {_x000D_
    echo 'Message has been sent';_x000D_
}
_x000D_
_x000D_
_x000D_

Turn on access and enjoy..! That is on Gmail account setting.

Turn On access

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

How to install multiple python packages at once using pip

pip install -r requirements.txt

and in the requirements.txt file you put your modules in a list, with one item per line.

  • Django=1.3.1

  • South>=0.7

  • django-debug-toolbar

PostgreSQL: role is not permitted to log in

The role you have created is not allowed to log in. You have to give the role permission to log in.

One way to do this is to log in as the postgres user and update the role:

psql -U postgres

Once you are logged in, type:

ALTER ROLE "asunotest" WITH LOGIN;

Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html

Windows Batch: How to add Host-Entries?

I would do it this way, so you won't end up with duplicate entries if the script is run multiple times.

@echo off

SET NEWLINE=^& echo.

FIND /C /I "ns1.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^62.116.159.4 ns1.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns2.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^217.160.113.37 ns2.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns3.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^89.146.248.4 ns3.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns4.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^74.208.254.4 ns4.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

Convert string to integer type in Go?

Here are three ways to parse strings into integers, from fastest runtime to slowest:

  1. strconv.ParseInt(...) fastest
  2. strconv.Atoi(...) still very fast
  3. fmt.Sscanf(...) not terribly fast but most flexible

Here's a benchmark that shows usage and example timing for each function:

package main

import "fmt"
import "strconv"
import "testing"

var num = 123456
var numstr = "123456"

func BenchmarkStrconvParseInt(b *testing.B) {
  num64 := int64(num)
  for i := 0; i < b.N; i++ {
    x, err := strconv.ParseInt(numstr, 10, 64)
    if x != num64 || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkAtoi(b *testing.B) {
  for i := 0; i < b.N; i++ {
    x, err := strconv.Atoi(numstr)
    if x != num || err != nil {
      b.Error(err)
    }
  }
}

func BenchmarkFmtSscan(b *testing.B) {
  for i := 0; i < b.N; i++ {
    var x int
    n, err := fmt.Sscanf(numstr, "%d", &x)
    if n != 1 || x != num || err != nil {
      b.Error(err)
    }
  }
}

You can run it by saving as atoi_test.go and running go test -bench=. atoi_test.go.

goos: darwin
goarch: amd64
BenchmarkStrconvParseInt-8      100000000           17.1 ns/op
BenchmarkAtoi-8                 100000000           19.4 ns/op
BenchmarkFmtSscan-8               2000000          693   ns/op
PASS
ok      command-line-arguments  5.797s

is there any IE8 only css hack?

So a recent question prompted me to notice a selector set hack for excluding IE 8 only.

.selector, #excludeIE8::before {} will cause IE 8 to throw out the entire selector set, while 5-7 and 9-11 will read it just fine. Any of the :: selectors (::first-line, ::before, ::first-letter, ::selection) will work, I've merely chosen ::before so the line reads accurately. Note that the goal of the fake ::before selector is to be fake, so be sure to change it to something else if you actually have an element with the ID excludeIE8

Interestingly enough, in modern browsers (FF 45-52, GC 49-57, Edge 25/13) a bad :: selector eats the entire selector set (dabblet demo). It seems that the last Windows version of Safari (and LTE IE 7, lol) doesn't have this behavior while still understanding ::before. Additionally, I can't find anything in the spec to indicate that this is intended behavior, and since it would cause breakage on any selector set containing: ::future-legitimate-pseudoelement... I'm inclined to say this is a bug- and one that'll nibble our rears in the future.


However, if you only want something at the property level (rather than the rule level), Ziga above had the best solution via appending  \9 (the space is key; do NOT copypaste that inline as it uses an nbsp):

/*property-level hacks:*/
/*Standards, Edge*/
prop:val;
/*lte ie 11*/
prop:val\9;
/*lte ie 8*/
prop:val \9;
/*lte ie 7*/
*prop:val;
/*lte ie 6*/
_prop:val;

/*other direction...*/
/*gte ie 8, NOT Edge*/
prop:val\0;

Side note, I feel like a dirty necromancer- but I wanted somewhere to document the exclude-IE8-only selector set hack I found today, and this seemed to be the most fitting place.

Creating multiline strings in JavaScript

There are multiple ways to achieve this

1. Slash concatenation

  var MultiLine=  '1\
    2\
    3\
    4\
    5\
    6\
    7\
    8\
    9';

2. regular concatenation

var MultiLine = '1'
+'2'
+'3'
+'4'
+'5';

3. Array Join concatenation

var MultiLine = [
'1',
'2',
'3',
'4',
'5'
].join('');

Performance wise, Slash concatenation (first one) is the fastest.

Refer this test case for more details regarding the performance

Update:

With the ES2015, we can take advantage of its Template strings feature. With it, we just need to use back-ticks for creating multi line strings

Example:

 `<h1>{{title}}</h1>
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div><label>name: </label>{{hero.name}}</div>
  `

Is there a way to delete all the data from a topic or delete the topic before every run?

Tested with kafka 0.10

1. stop zookeeper & Kafka server,
2. then go to 'kafka-logs' folder , there you will see list of kafka topic folders, delete folder with topic name
3. go to 'zookeeper-data' folder , delete data inside that.
4. start zookeeper & kafka server again.

Note : if you are deleting topic folder/s inside kafka-logs but not from zookeeper-data folder, then you will see topics are still there.

Http 415 Unsupported Media type error with JSON

Add MappingJackson2HttpMessageConverter manually in configuration solved the problem for me :

@EnableWebMvc
@Configuration
@ComponentScan
public class RestConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        super.configureMessageConverters(messageConverters);
    }
}

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

flutter corner radius with transparent background

showModalBottomSheet(
   context: context,
   builder: (context) => Container(
            color: Color(0xff757575), //background color 
            child:  new Container(
                decoration: new BoxDecoration(
                    color: Colors.blue,
                    borderRadius: new BorderRadius.only(
                        topLeft:  const  Radius.circular(40.0),
                        topRight: const  Radius.circular(40.0))
                ),
              child: new Center(
                child: new Text("Hi modal sheet"),
              )

     

 ),

)

This is will make your container color the same as the background color. And there will be a child container of the same height-width with blue color. This will make the corner with the same color as the background color.

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

You need to load your JNI library.

System.loadLibrary loads the DLL from the JVM path (JDK bin path).

If you want to load an explicit file with a path, use System.load()

See also: Difference between System.load() and System.loadLibrary in Java

Reading a file line by line in Go

In Go 1.1 and newer the most simple way to do this is with a bufio.Scanner. Here is a simple example that reads lines from a file:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.Open("/path/to/file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

This is the cleanest way to read from a Reader line by line.

There is one caveat: Scanner does not deal well with lines longer than 65536 characters. If that is an issue for you then then you should probably roll your own on top of Reader.Read().

How to change the style of the title attribute inside an anchor tag?

I thought i'd post my 20 lines JavaScript solution here. It is not perfect, but may be useful for some depending on what you need from your tooltips.

When to use it

  • Automatically styles the tooltip for all HTML elements with a TITLE attribute defined (this includes elements dynamically added to the document in the future)
  • No Javascript/HTML changes or hacks required for every tooltip (just the TITLE attribute, semantically clear)
  • Very light (adds about 300 bytes gzipped and minified)
  • You want only a very basic styleable tooltip

When NOT to use

  • Requires jQuery, so do not use if you don't use jQuery
  • Bad support for nested elements that both have tooltips
  • You need more than one tooltip on the screen at the same time
  • You need the tooltip to disappear after some time

The code

// Use a closure to keep vars out of global scope
(function () {
    var ID = "tooltip", CLS_ON = "tooltip_ON", FOLLOW = true,
    DATA = "_tooltip", OFFSET_X = 20, OFFSET_Y = 10,
    showAt = function (e) {
        var ntop = e.pageY + OFFSET_Y, nleft = e.pageX + OFFSET_X;
        $("#" + ID).html($(e.target).data(DATA)).css({
            position: "absolute", top: ntop, left: nleft
        }).show();
    };
    $(document).on("mouseenter", "*[title]", function (e) {
        $(this).data(DATA, $(this).attr("title"));
        $(this).removeAttr("title").addClass(CLS_ON);
        $("<div id='" + ID + "' />").appendTo("body");
        showAt(e);
    });
    $(document).on("mouseleave", "." + CLS_ON, function (e) {
        $(this).attr("title", $(this).data(DATA)).removeClass(CLS_ON);
        $("#" + ID).remove();
    });
    if (FOLLOW) { $(document).on("mousemove", "." + CLS_ON, showAt); }
}());

Paste it anywhere, it should work even when you run this code before the DOM is ready (it just won't show your tooltips until DOM is ready).

Customize

You can change the var declarations on the second line to customize it a bit.

var ID = "tooltip"; // The ID of the styleable tooltip
var CLS_ON = "tooltip_ON"; // Does not matter, make it somewhat unique
var FOLLOW = true; // TRUE to enable mouse following, FALSE to have static tooltips
var DATA = "_tooltip"; // Does not matter, make it somewhat unique
var OFFSET_X = 20, OFFSET_Y = 10; // Tooltip's distance to the cursor

Style

You can now style your tooltips using the following CSS:

#tooltip {
    background: #fff;
    border: 1px solid red;
    padding: 3px 10px;
}

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

I just tested benmajor's GitHub jQuery Touch Events plugin for both 1.4 and 1.7+ versions of jQuery. It is lightweight and works perfectly with both on and bind while providing support for an exhaustive set of touch events.

How to get index of an item in java.util.Set

you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.

How do I execute a program from Python? os.system fails due to spaces in path

For python >= 3.5 subprocess.run should be used in place of subprocess.call

https://docs.python.org/3/library/subprocess.html#older-high-level-api

import subprocess
subprocess.run(['notepad.exe', 'test.txt'])

What is the shortest function for reading a cookie by name in JavaScript?

Just to throw my hat in the race, here's my proposal:

function getCookie(name) {
   const cookieDict = document.cookie.split(';')
        .map((x)=>x.split('='))
        .reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, Object());
    return cookieDict[name];
}

The above code generates a dict that stores cookies as key-value pairs (i.e., cookieDict), and afterwards accesses the property name to retrieve the cookie.

This could effectively be expressed as a one-liner, but this is only for the brave:

document.cookie.split(';').map((x)=>x.split('=')).reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, {})[name]

The absolute best approach would be to generate cookieDict at page load and then throughout the page lifecycle just access individual cookies by calling cookieDict['cookiename'].

What is the purpose of meshgrid in Python / NumPy?

The purpose of meshgrid is to create a rectangular grid out of an array of x values and an array of y values.

So, for example, if we want to create a grid where we have a point at each integer value between 0 and 4 in both the x and y directions. To create a rectangular grid, we need every combination of the x and y points.

This is going to be 25 points, right? So if we wanted to create an x and y array for all of these points, we could do the following.

x[0,0] = 0    y[0,0] = 0
x[0,1] = 1    y[0,1] = 0
x[0,2] = 2    y[0,2] = 0
x[0,3] = 3    y[0,3] = 0
x[0,4] = 4    y[0,4] = 0
x[1,0] = 0    y[1,0] = 1
x[1,1] = 1    y[1,1] = 1
...
x[4,3] = 3    y[4,3] = 4
x[4,4] = 4    y[4,4] = 4

This would result in the following x and y matrices, such that the pairing of the corresponding element in each matrix gives the x and y coordinates of a point in the grid.

x =   0 1 2 3 4        y =   0 0 0 0 0
      0 1 2 3 4              1 1 1 1 1
      0 1 2 3 4              2 2 2 2 2
      0 1 2 3 4              3 3 3 3 3
      0 1 2 3 4              4 4 4 4 4

We can then plot these to verify that they are a grid:

plt.plot(x,y, marker='.', color='k', linestyle='none')

enter image description here

Obviously, this gets very tedious especially for large ranges of x and y. Instead, meshgrid can actually generate this for us: all we have to specify are the unique x and y values.

xvalues = np.array([0, 1, 2, 3, 4]);
yvalues = np.array([0, 1, 2, 3, 4]);

Now, when we call meshgrid, we get the previous output automatically.

xx, yy = np.meshgrid(xvalues, yvalues)

plt.plot(xx, yy, marker='.', color='k', linestyle='none')

enter image description here

Creation of these rectangular grids is useful for a number of tasks. In the example that you have provided in your post, it is simply a way to sample a function (sin(x**2 + y**2) / (x**2 + y**2)) over a range of values for x and y.

Because this function has been sampled on a rectangular grid, the function can now be visualized as an "image".

enter image description here

Additionally, the result can now be passed to functions which expect data on rectangular grid (i.e. contourf)

Free c# QR-Code generator

Take a look QRCoder - pure C# open source QR code generator. Can be used in three lines of code

QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBoxQRCode.Text, QRCodeGenerator.ECCLevel.Q);
pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20);

ngModel cannot be used to register form controls with a parent formGroup directive

I just got this error because I did not enclose all my form controls within a div with a formGroup attribute.

For example, this will throw an error

<div [formGroup]='formGroup'>
</div>
<input formControlName='userName' />

This can be quite easy to miss if its a particularly long form.

Hive query output to file

  1. Create an external table
  2. Insert data into the table
  3. Optional drop the table later, which wont delete that file since it is an external table

Example:

Creating external table to store the query results at '/user/myName/projectA_additionaData/'

CREATE EXTERNAL TABLE additionaData
(
     ID INT,
     latitude STRING,
     longitude STRING
)
COMMENT 'Additional Data gathered by joining of the identified cities with latitude and longitude data' 
ROW FORMAT DELIMITED FIELDS
TERMINATED BY ',' STORED AS TEXTFILE location '/user/myName/projectA_additionaData/';

Feeding the query results into the temp table

 insert into additionaData 
     Select T.ID, C.latitude, C.longitude 
     from TWITER  
     join CITY C on (T.location_name = C.location);

Dropping the temp table

drop table additionaData

Linq style "For Each"

Using the ToList() extension method is your best option:

someValues.ToList().ForEach(x => list.Add(x + 1));

There is no extension method in the BCL that implements ForEach directly.


Although there's no extension method in the BCL that does this, there is still an option in the System namespace... if you add Reactive Extensions to your project:

using System.Reactive.Linq;

someValues.ToObservable().Subscribe(x => list.Add(x + 1));

This has the same end result as the above use of ToList, but is (in theory) more efficient, because it streams the values directly to the delegate.

How to give color to each class in scatter plot in R?

One way is to use the lattice package and xyplot():

R> DF <- data.frame(x=1:10, y=rnorm(10)+5, 
+>                  z=sample(letters[1:3], 10, replace=TRUE))
R> DF
    x       y z
1   1 3.91191 c
2   2 4.57506 a
3   3 3.16771 b
4   4 5.37539 c
5   5 4.99113 c
6   6 5.41421 a
7   7 6.68071 b
8   8 5.58991 c
9   9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))

By giving explicit grouping information via variable z, you obtain different colors. You can specify colors etc, see the lattice documentation.

Because z here is a factor variable for which we obtain the levels (== numeric indices), you can also do

R> with(DF, plot(x, y, col=z))

but that is less transparent (to me, at least :) then xyplot() et al.

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

How to check ASP.NET Version loaded on a system?

You can see which version gets executed when you load the page with Google Chrome + developer tools (preinstalled) or Firefox + Firebug (add-on).

I use Google Chrome:

  1. Open Chrome and use Ctrl+Shift+I to open the developer tools.
  2. Go to the "Network" Tab
  3. Click on the small button at the bottom "Preserve log upon Navigation"
  4. Load any of your pages
  5. Click on the response header

It looks like this:

enter image description here

Hadoop: «ERROR : JAVA_HOME is not set»

Copy this export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk to hadoop-env.sh file.

JAVA_HOME is the location where java binaries are present.

Check if string has space in between (or anywhere)

It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.

var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true

ORA-00054: resource busy and acquire with NOWAIT specified

You'll have to wait. The session that was killed was in the middle of a transaction and updated lots of records. These records have to be rollbacked and some background process is taking care of that. In the meantime you cannot modify the records that were touched.

What is the difference between task and thread?

In computer science terms, a Task is a future or a promise. (Some people use those two terms synonymously, some use them differently, nobody can agree on a precise definition.) Basically, a Task<T> "promises" to return you a T, but not right now honey, I'm kinda busy, why don't you come back later?

A Thread is a way of fulfilling that promise. But not every Task needs a brand-new Thread. (In fact, creating a thread is often undesirable, because doing so is much more expensive than re-using an existing thread from the thread pool. More on that in a moment.) If the value you are waiting for comes from the filesystem or a database or the network, then there is no need for a thread to sit around and wait for the data when it can be servicing other requests. Instead, the Task might register a callback to receive the value(s) when they're ready.

In particular, the Task does not say why it is that it takes such a long time to return the value. It might be that it takes a long time to compute, or it might that it takes a long time to fetch. Only in the former case would you use a Thread to run a Task. (In .NET, threads are freaking expensive, so you generally want to avoid them as much as possible and really only use them if you want to run multiple heavy computations on multiple CPUs. For example, in Windows, a thread weighs 12 KiByte (I think), in Linux, a thread weighs as little as 4 KiByte, in Erlang/BEAM even just 400 Byte. In .NET, it's 1 MiByte!)

What is the difference between dynamic and static polymorphism in Java?

method overloading is an example of compile time/static polymorphism because method binding between method call and method definition happens at compile time and it depends on the reference of the class (reference created at compile time and goes to stack).

method overriding is an example of run time/dynamic polymorphism because method binding between method call and method definition happens at run time and it depends on the object of the class (object created at runtime and goes to the heap).

How to sparsely checkout only one single file from a git repository?

I don’t see what worked for me listed out here so I will include it should anybody be in my situation.

My situation, I have a remote repository of maybe 10,000 files and I need to build an RPM file for my Linux system. The build of the RPM includes a git clone of everything. All I need is one file to start the RPM build. I can clone the entire source tree which does what I need but it takes an extra two minutes to download all those files when all I need is one. I tried to use the git archive option discussed and I got “fatal: Operation not supported by protocol.” It seems I have to get some sort of archive option enabled on the server and my server is maintained by bureaucratic thugs that seem to enjoy making it difficult to get things done.

What I finally did was I went into the web interface for bitbucket and viewed the one file I needed. I did a right click on the link to download a raw copy of the file and selected “copy shortcut” from the resulting popup. I could not just download the raw file because I needed to automate things and I don’t have a browser interface on my Linux server.

For the sake of discussion, that resulted in the URL:

https://ourArchive.ourCompany.com/projects/ThisProject/repos/data/raw/foo/bar.spec?at=refs%2Fheads%2FTheBranchOfInterest

I could not directly download this file from the bitbucket repository because I needed to sign in first. After a little digging, I found this worked: On Linux:

echo "myUser:myPass123"| base64
bXlVc2VyOm15UGFzczEyMwo=

curl -H 'Authorization: Basic bXlVc2VyOm15UGFzczEyMwo=' 'https://ourArchive.ourCompany.com/projects/ThisProject/repos/data/raw/foo/bar.spec?at=refs%2Fheads%2FTheBranchOfInterest' > bar.spec

This combination allowed me to download the one file I needed to build everything else.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I think AutoCAD hijacked mine. The solution which worked for me was to hijack it back. I got this from https://forums.autodesk.com/t5/navisworks-api/could-not-load-file-or-assembly-newtonsoft-json/td-p/7028055?profile.language=en - yeah, the Internet works in mysterious ways.

// in your initilizer ...
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

.....

private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
    if (args.Name.Contains("Newtonsoft.Json"))
    {
        string assemblyFileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Newtonsoft.Json.dll";
        return Assembly.LoadFrom(assemblyFileName);
    }
    else
        return null;
}

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

The minimum required:

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MessageSender {

    public static void sendHardCoded() throws AddressException, MessagingException {
        String to = "[email protected]";
        final String from = "[email protected]";

        Properties properties = new Properties();
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        Session session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, "BeNice");
                    }
                });

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject("Hello");
        message.setText("What's up?");

        Transport.send(message);
    }

}

Escaping backslash in string - javascript

Slightly hacky, but it works:

_x000D_
_x000D_
const input = '\text';_x000D_
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();_x000D_
_x000D_
console.log({ input, output });_x000D_
// { input: '\text', output: '\\text' }
_x000D_
_x000D_
_x000D_

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

How to dynamically change a web page's title?

The simplest way is to delete <title> tag from index.html, and include

<head>
<title> Website - The page </title></head>

in every page in the web. Spiders will find this and will be shown in search results :)

angular2 manually firing click event on particular element

If you want to imitate click on the DOM element like this:

<a (click)="showLogin($event)">login</a>

and have something like this on the page:

<li ngbDropdown>
    <a ngbDropdownToggle id="login-menu">
        ...
    </a>
 </li>

your function in component.ts should be like this:

showLogin(event) {
   event.stopPropagation();
   document.getElementById('login-menu').click();
}

How to print the current time in a Batch-File?

we can easily print the current time and date using echo and system variables as below.

echo %DATE% %TIME%

output example: 13-Sep-19 15:53:05.62

The property 'value' does not exist on value of type 'HTMLElement'

Problem:

error Property 'text' does not exist on type 'HTMLElement'

Solution: in typeScript we need to cast document.getElementById() which returns type HTMLElement in < HTMLScriptElement >

So we can do it by by following way to resolve the error as expected by typescript.js

Code: var content: string = ( < HTMLScriptElement > document.getElementById(contentId)).text;

It worked for me.. hope it works for you as well.

Date / Timestamp to record when a record was added to the table?

You can make a default constraint on this column that will put a default getdate() as a value.

Example:

alter table dbo.TABLE 
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN

How to close a JavaFX application on window close?

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        Platform.exit();
        System.exit(0);
    }
});

How to use readline() method in Java?

I advise you to go with Scanner instead of DataInputStream. Scanner is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner.

Example

Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

your column value is already in database table it means your table column is Unique you should change your value and try again

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

Python 3 handles strings a bit different. Originally there was just one type for strings: str. When unicode gained traction in the '90s the new unicode type was added to handle Unicode without breaking pre-existing code1. This is effectively the same as str but with multibyte support.

In Python 3 there are two different types:

  • The bytes type. This is just a sequence of bytes, Python doesn't know anything about how to interpret this as characters.
  • The str type. This is also a sequence of bytes, but Python knows how to interpret those bytes as characters.
  • The separate unicode type was dropped. str now supports unicode.

In Python 2 implicitly assuming an encoding could cause a lot of problems; you could end up using the wrong encoding, or the data may not have an encoding at all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to guess) is often a lot better and much more in line with the "Python philosophy" of "explicit is better than implicit".

This change is incompatible with Python 2 as many return values have changed, leading to subtle problems like this one; it's probably the main reason why Python 3 adoption has been so slow. Since Python doesn't have static typing2 it's impossible to change this automatically with a script (such as the bundled 2to3).

  • You can convert str to bytes with bytes('h€llo', 'utf-8'); this should produce b'H\xe2\x82\xacllo'. Note how one character was converted to three bytes.
  • You can convert bytes to str with b'H\xe2\x82\xacllo'.decode('utf-8').

Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.

In your specific piece of code, nextline is of type bytes, not str, reading stdout and stdin from subprocess changed in Python 3 from str to bytes. This is because Python can't be sure which encoding this uses. It probably uses the same as sys.stdin.encoding (the encoding of your system), but it can't be sure.

You need to replace:

sys.stdout.write(nextline)

with:

sys.stdout.write(nextline.decode('utf-8'))

or maybe:

sys.stdout.write(nextline.decode(sys.stdout.encoding))

You will also need to modify if nextline == '' to if nextline == b'' since:

>>> '' == b''
False

Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.


1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A') and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.

2 Yes, you can use function annotations, but it's a comparatively new feature and little used.

Why doesn't height: 100% work to expand divs to the screen height?

Since nobody has mentioned this..

Modern Approach:

As an alternative to setting both the html/body element's heights to 100%, you could also use viewport-percentage lengths:

5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

In this instance, you could use the value 100vh (which is the height of the viewport) - (example)

body {
    height: 100vh;
}

Setting a min-height also works. (example)

body {
    min-height: 100vh;
}

These units are supported in most modern browsers - support can be found here.

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

_x000D_
_x000D_
// TypeError: functionOne is not a function_x000D_
functionOne();_x000D_
_x000D_
var functionOne = function() {_x000D_
  console.log("Hello!");_x000D_
};
_x000D_
_x000D_
_x000D_

And, a function declaration:

_x000D_
_x000D_
// Outputs: "Hello!"_x000D_
functionTwo();_x000D_
_x000D_
function functionTwo() {_x000D_
  console.log("Hello!");_x000D_
}
_x000D_
_x000D_
_x000D_

Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.

_x000D_
_x000D_
'use strict';    _x000D_
{ // note this block!_x000D_
  function functionThree() {_x000D_
    console.log("Hello!");_x000D_
  }_x000D_
}_x000D_
functionThree(); // ReferenceError
_x000D_
_x000D_
_x000D_

Filter output in logcat by tagname

Here is how I create a tag:

private static final String TAG = SomeActivity.class.getSimpleName();
 Log.d(TAG, "some description");

You could use getCannonicalName

Here I have following TAG filters:

  • any (*) View - VERBOSE
  • any (*) Activity - VERBOSE
  • any tag starting with Xyz(*) - ERROR
  • System.out - SILENT (since I am using Log in my own code)

Here what I type in terminal:

$  adb logcat *View:V *Activity:V Xyz*:E System.out:S

adb command for getting ip address assigned by operator

According to comments: netcfg was removed in Android 6

Try

adb shell netcfg

Or

adb shell <device here or leave out if one device>
shell@android:/ $netcfg

What does the construct x = x || y mean?

double pipe operator

is this example usefull?

var section = document.getElementById('special');
if(!section){
     section = document.getElementById('main');
}

can also be

var section = document.getElementById('special') || document.getElementById('main');

How can I convert JSON to a HashMap using Gson?

Below is supported since gson 2.8.0

public static Type getMapType(Class keyType, Class valueType){
    return TypeToken.getParameterized(HashMap.class, keyType, valueType).getType();
}

public static  <K,V> HashMap<K,V> fromMap(String json, Class<K> keyType, Class<V> valueType){
    return gson.fromJson(json, getMapType(keyType,valueType));
}

Maintaining Session through Angular.js

You can also try to make service based on window.sessionStorage or window.localStorage to keep state information between page reloads. I use it in the web app which is partially made in AngularJS and page URL is changed in "the old way" for some parts of workflow. Web storage is supported even by IE8. Here is angular-webstorage for convenience.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Is a Java hashmap search really O(1)?

O(1+n/k) where k is the number of buckets.

If implementation sets k = n/alpha then it is O(1+alpha) = O(1) since alpha is a constant.

Converting a character code to char (VB.NET)

you can also use

Dim intValue as integer = 65  ' letter A for instance
Dim strValue As String = Char.ConvertFromUtf32(intValue)

this doesn't requirement Microsoft.VisualBasic reference

How to access your website through LAN in ASP.NET

If you use IIS Express via Visual Studio instead of the builtin ASP.net host, you can achieve this.

Binding IIS Express to an IP Address

How to find the index of an element in an int array?

Binary search: Binary search can also be used to find the index of the array element in an array. But the binary search can only be used if the array is sorted. Java provides us with an inbuilt function which can be found in the Arrays library of Java which will rreturn the index if the element is present, else it returns -1. The complexity will be O(log n). Below is the implementation of Binary search.

public static int findIndex(int arr[], int t) { 
   int index = Arrays.binarySearch(arr, t); 
   return (index < 0) ? -1 : index; 
} 

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

How to generate the "create table" sql statement for an existing table in postgreSQL

DataGrip has the same functionality as pgAdmin. You can right click on a table and you will see option to auto-generate create table statement.Screenshot from DataGrip v2020.1.5

Set order of columns in pandas dataframe

Here is a solution I use very often. When you have a large data set with tons of columns, you definitely do not want to manually rearrange all the columns.

What you can and, most likely, want to do is to just order the first a few columns that you frequently use, and let all other columns just be themselves. This is a common approach in R. df %>%select(one, two, three, everything())

So you can first manually type the columns that you want to order and to be positioned before all the other columns in a list cols_to_order.

Then you construct a list for new columns by combining the rest of the columns:

new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())

After this, you can use the new_columns as other solutions suggested.

import pandas as pd
frame = pd.DataFrame({
    'one thing': [1, 2, 3, 4],
    'other thing': ['a', 'e', 'i', 'o'],
    'more things': ['a', 'e', 'i', 'o'],
    'second thing': [0.1, 0.2, 1, 2],
})

cols_to_order = ['one thing', 'second thing']
new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())
frame = frame[new_columns]

   one thing  second thing other thing more things
0          1           0.1           a           a
1          2           0.2           e           e
2          3           1.0           i           i
3          4           2.0           o           o

Changing image size in Markdown

For R-Markdown, neither of the above solutions worked for me, so I turned to regular LaTeX syntax, which works just fine.

\begin{figure}
 \includegraphics[width=300pt, height = 125 pt]{drawing.jpg}
\end{figure}

Then you can use e.g. the \begin{center} statement to center the image.

Hibernate error: ids for this class must be manually assigned before calling save():

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;

it will handle incrementing id generation for you.

Start an external application from a Google Chrome Extension?

You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.

E.g. you have the users set things up so that some-app:// links start "SomeApp", and then in my-awesome-extension you open a tab pointing to some-app://some-data-the-app-wants, and you're good to go!

Setting the number of map tasks and reduce tasks

I agree the number mapp task depends upon the input split but in some of the scenario i could see its little different

case-1 I created a simple mapp task only it creates 2 duplicate out put file (data ia same) command I gave below

bin/hadoop jar contrib/streaming/hadoop-streaming-1.2.1.jar -D mapred.reduce.tasks=0 -input /home/sample.csv -output /home/sample_csv112.txt -mapper /home/amitav/workpython/readcsv.py

Case-2 So I restrcted the mapp task to 1 the out put came correctly with one output file but one reducer also lunched in the UI screen although I restricted the reducer job. The command is given below.

bin/hadoop jar contrib/streaming/hadoop-streaming-1.2.1.jar -D mapred.map.tasks=1 mapred.reduce.tasks=0 -input /home/sample.csv -output /home/sample_csv115.txt -mapper /home/amitav/workpython/readcsv.py

How do I generate random numbers in Dart?

Use Dart Generators, that is used to produce a sequence of number or values.

 main(){ 
       print("Sequence Number");
       oddnum(10).forEach(print);
     }
    Iterable<int> oddnum(int num) sync*{
     int k=num;
     while(k>=0){
       if(k%2==1){
        yield k;
       }
      k--;
     } 
}

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

What is the command to exit a Console application in C#?

Console applications will exit when the main function has finished running. A "return" will achieve this.

    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("I'm running!");
            return; //This will exit the console application's running thread
        }
    }

If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:

    System.Environment.Exit(-1);

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

Joining pandas dataframes by column names

you need to make county_ID as index for the right frame:

frame_2.join ( frame_1.set_index( [ 'county_ID' ], verify_integrity=True ),
               on=[ 'countyid' ], how='left' )

for your information, in pandas left join breaks when the right frame has non unique values on the joining column. see this bug.

so you need to verify integrity before joining by , verify_integrity=True

Not able to launch IE browser using Selenium2 (Webdriver) with Java

  1. Go to IE->Tools->Internet Options.
  2. Go to Security tab.
  3. Either Enable/Disable the protected mode for all(Internet, Local Intranet, Trusted Sites & Restricted Sites.)

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

Let's break down the full URL that a client would type into their address bar to reach your servlet:

http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo

The parts are:

  1. scheme: http
  2. hostname: www.example.com
  3. port: 80
  4. context path: awesome-application
  5. servlet path: path/to/servlet
  6. path info: path/info
  7. query: a=1&b=2
  8. fragment: boo

The request URI (returned by getRequestURI) corresponds to parts 4, 5 and 6.

(incidentally, even though you're not asking for this, the method getRequestURL would give you parts 1, 2, 3, 4, 5 and 6).

Now:

  • part 4 (the context path) is used to select your particular application out of many other applications that may be running in the server
  • part 5 (the servlet path) is used to select a particular servlet out of many other servlets that may be bundled in your application's WAR
  • part 6 (the path info) is interpreted by your servlet's logic (e.g. it may point to some resource controlled by your servlet).
  • part 7 (the query) is also made available to your servlet using getQueryString
  • part 8 (the fragment) is not even sent to the server and is relevant and known only to the client

The following always holds (except for URL encoding differences):

requestURI = contextPath + servletPath + pathInfo

The following example from the Servlet 3.0 specification is very helpful:


Note: image follows, I don't have the time to recreate in HTML:

enter image description here

jQuery: How can I show an image popup onclick of the thumbnail?

This is the most popular (9500 stars) and light weight (20KB minify, 7.5KB minify+gzip) popup gallery I think: Magnific-Popup

Git Bash won't run my python files?

Tried multiple of these, I switched to Cygwin instead which fixed python and some other problems I was having on Windows:

https://www.cygwin.com/

How to convert xml into array in php?

See https://github.com/gaarf/XML-string-to-PHP-array/blob/master/xmlstr_to_array.php

<?php
/**
  * convert xml string to php array - useful to get a serializable value
  *
  * @param string $xmlstr
  * @return array
  *
  * @author Adrien aka Gaarf & contributors
  * @see http://gaarf.info/2009/08/13/xml-string-to-php-array/
*/
function xmlstr_to_array($xmlstr) {
  $doc = new DOMDocument();
  $doc->loadXML($xmlstr);
  $root = $doc->documentElement;
  $output = domnode_to_array($root);
  $output['@root'] = $root->tagName;
  return $output;
}
function domnode_to_array($node) {
  $output = array();
  switch ($node->nodeType) {
    case XML_CDATA_SECTION_NODE:
    case XML_TEXT_NODE:
      $output = trim($node->textContent);
    break;
    case XML_ELEMENT_NODE:
      for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
        $child = $node->childNodes->item($i);
        $v = domnode_to_array($child);
        if(isset($child->tagName)) {
          $t = $child->tagName;
          if(!isset($output[$t])) {
            $output[$t] = array();
          }
          $output[$t][] = $v;
        }
        elseif($v || $v === '0') {
          $output = (string) $v;
        }
      }
      if($node->attributes->length && !is_array($output)) { //Has attributes but isn't an array
        $output = array('@content'=>$output); //Change output into an array.
      }
      if(is_array($output)) {
        if($node->attributes->length) {
          $a = array();
          foreach($node->attributes as $attrName => $attrNode) {
            $a[$attrName] = (string) $attrNode->value;
          }
          $output['@attributes'] = $a;
        }
        foreach ($output as $t => $v) {
          if(is_array($v) && count($v)==1 && $t!='@attributes') {
            $output[$t] = $v[0];
          }
        }
      }
    break;
  }
  return $output;
}

CSS3 :unchecked pseudo-class

I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.

input[type="checkbox"] {
  // Unchecked Styles
}
input[type="checkbox"]:checked {
  // Checked Styles
}

I apologize for bringing up an old thread but felt like it could have used a better answer.

EDIT (3/3/2016):

W3C Specs state that :not(:checked) as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"] selector. See example below for clarification.

input[type="checkbox"] {
  /* Base Styles aka unchecked */
  font-weight: 300; // Will be overwritten by :checked
  font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
  /* Explicit Unchecked Styles */
  border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
  /* Checked Styles */
  font-weight: 900; // Use a bold font when checked
}

Without using :not(:checked) in the example above the :checked selector would have needed to use a border: none; to achieve the same affect.

Use the input[type="checkbox"] for base styling to reduce duplication.

Use the input[type="checkbox"]:not(:checked) for explicit unchecked styles that you do not want to apply to the checked state.

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

Select default option value from typescript angular 6

i manage this by doing like this =>

<select class="form-control" 
        [(ngModel)]="currentUserID"
        formControlName="users">
        <option value='-1'>{{"select a user" | translate}}</option>
            <option 
            *ngFor="let user of users"
            value="{{user.id}}">
            {{user.firstname}}
   </option>
</select>

How to find if directory exists in Python

So close! os.path.isdir returns True if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns False.

Vibrate and Sound defaults on notification

Some dummy codes might help you.

   private static NotificationCompat.Builder buildNotificationCommon(Context _context, .....) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(_context)
            .setWhen(System.currentTimeMillis()).......;
     //Vibration
        builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });

     //LED
        builder.setLights(Color.RED, 3000, 3000);

     //Ton
        builder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));

    return builder;
   }

Add below permission for Vibration in AndroidManifest.xml file

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

setting JAVA_HOME & CLASSPATH in CentOS 6

I created a folder named a in /home/prasanth and copied your code to a file named A.java. I compiled from /home/prasanth as javac a/A.java and run javac a.A. I got output as

a!

How to add a "open git-bash here..." context menu to the windows explorer?

I had a similar issue and I did this.

Step 1 : Type "regedit" in start menu

Step 2 : Run the registry editor

Step 3 : Navigate to HKEY_CURRENT_USER\SOFTWARE\Classes\Directory\Background\shell

Step 4 : Right-click on "shell" and choose New > Key. name the Key "Bash"

Right click on "shell" and choose New > Key. name the Key "Bash"

Step 5 : Modify the value and set it to "open in Bash" This is the text that appears in the right click.

enter image description here

enter image description here

Step 6 : Create a new key under Bash and name it "command". Set the value of this key to your git-bash.exe path.

enter image description here

enter image description here

enter image description here

Close the registry editor.

You should now be able to see the option in right click menu in explorer

PS Git Bash by default picks up the current directory.

EDIT : If you want a one click approach, check Ozesh's solution below

How do I unbind "hover" in jQuery?

Unbind the mouseenter and mouseleave events individually or unbind all events on the element(s).

$(this).unbind('mouseenter').unbind('mouseleave');

or

$(this).unbind();  // assuming you have no other handlers you want to keep

Difference between Apache CXF and Axis

Keep in mind, I'm completely biased (PMC Chair of CXF), but my thoughts:

From a strictly "can the project do what I need it to do" perspective, both are pretty equivalent. There some "edge case" things that CXF can do that Axis 2 cannot and vice versa. But for 90% of the use cases, either will work fine.

Thus, it comes down to a bunch of other things other than "check box features".

  • API - CXF pushes "standards based" API's (JAX-WS compliant) whereas Axis2 general goes toward proprietary things. That said, even CXF may require uses of proprietary API's to configure/control various things outside the JAX-WS spec. For REST, CXF also uses standard API's (JAX-RS compliant) instead of proprietary things. (Yes, I'm aware of the JAX-WS runtime in Axis2, but the tooling and docs and everything doesn't target it)

  • Community aspects and supportability - CXF prides itself on responding to issues and making "fixpacks" available to users. CXF did 12 fixpacks for 2.0.x (released two years ago, so about every 2 months), 6 fixpacks to 2.1.x, and now 3 for 2.2.x. Axis2 doesn't really "support" older versions. Unless a "critical" issue is hit, you may need to wait till the next big release (they average about every 9-10 months or so) to get fixes. (although, with either, you can grab the source code and patch/fix yourself. Gotta love open source.)

  • Integration - CXF has much better Spring integration if you use Spring. All the configuration and such is done through Spring. Also, people tend to consider CXF as more "embeddable" (I've never looked at Axis2 from this perspective) into other applications. Not sure if things like that matter to you.

  • Performance - they both perform very well. I think Axis2's proprietary ADB databinding is a bit faster than CXF, but if you use JAXB (standards based API's again), CXF is a bit faster. When using more complex scenarios like WS-Security, the underlying security "engine" (WSS4J) is the same for both so the performance is completely comparable.

Not sure if that answers the question at all. Hope it at least provides some information.

:-)

Dan

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

How to configure logging to syslog in Python?

I add a little extra comment just in case it helps anyone because I found this exchange useful but needed this little extra bit of info to get it all working.

To log to a specific facility using SysLogHandler you need to specify the facility value. Say for example that you have defined:

local3.* /var/log/mylog

in syslog, then you'll want to use:

handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)

and you also need to have syslog listening on UDP to use localhost instead of /dev/log.

"multiple target patterns" Makefile error

I had it on the Makefile

MAPS+=reverse/db.901:550:2001.ip6.arpa 
lastserial:  ${MAPS}
    ./updateser ${MAPS}

It's because of the : in the file name. I solved this with

                      -------- notice
                     /    /
                    v    v
MAPS+=reverse/db.901\:550\:2001.ip6.arpa
lastserial:  ${MAPS}
    ./updateser ${MAPS}

How can I generate a 6 digit unique number?

If you want it to start at 000001 and go to 999999:

$num_str = sprintf("%06d", mt_rand(1, 999999));

Mind you, it's stored as a string.

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

  1. Make a jar file from your applet class and META-INF/MANIFEST.MF file.
  2. Sign your jar file with your certificate.
  3. Configure your local site permissions as > file:///C:/ or http: //localhost:8080
  4. Then run your html document on Intenet Explorer on Windows.(Not Google Chrome !)

Detect when an HTML5 video finishes

Here is a simple approach which triggers when the video ends.

<html>
<body>

    <video id="myVideo" controls="controls">
        <source src="video.mp4" type="video/mp4">
        etc ...
    </video>

</body>
<script type='text/javascript'>

    document.getElementById('myVideo').addEventListener('ended', function(e) {

        alert('The End');

    })

</script>
</html> 

In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.

Set focus on textbox in WPF

None of this worked for me as I was using a grid rather than a StackPanel.

I finally found this example: http://spin.atomicobject.com/2013/03/06/xaml-wpf-textbox-focus/

and modified it to this:

In the 'Resources' section:

    <Style x:Key="FocusTextBox" TargetType="Grid">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=textBoxName, Path=IsVisible}" Value="True">
                <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=textBoxName}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

In my grid definition:

<Grid Style="{StaticResource FocusTextBox}" />

regex pattern to match the end of a string

Something like this should work: /([^/]*)$

What language are you using? End-of-string regex signifiers can vary in different languages.

Calling Non-Static Method In Static Method In Java

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

Changing color of Twitter bootstrap Nav-Pills

This is specific to Bootstrap 4.0.

HTML

<ul class="nav nav-pills">
  <li class="nav-item">
    <a class="nav-link nav-link-color" href="#about">home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link nav-link-color"  href="#contact">contact</a>
  </li>
</ul>

CSS

.nav-pills > li > a.active {
  background-color: #ffffff !important;
  color: #ffffff !important;
}

.nav-pills > li > a:hover {
  color: #ffffff !important;
}

.nav-link-color {
  color: #ffffff;
}

How to get the mobile number of current sim card in real device?

You can use the TelephonyManager to do this:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The documentation for getLine1Number() says this method will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

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

(You shouldn't use TelephonyManager.getDefault() to get the TelephonyManager as that is a private undocumented API call and may change in future.)

Splitting a table cell into two columns in HTML

I came here for a similar problem I was facing with my table headers.

@MrMisterMan's answer, as well as others, were really helpful, but the borders were beating my game. So, I did some research to find the use rowspan.

Here's what I did and I guess it might help others facing something similar.

_x000D_
_x000D_
<table style="width: 100%; margin-top: 10px; font-size: 0.8em;" border="1px">_x000D_
    <tr align="center" >_x000D_
        <th style="padding:2.5px; width: 10%;" rowspan="2">Item No</th>_x000D_
        <th style="padding:2.5px; width: 55%;" rowspan="2">DESCRIPTION</th>_x000D_
        <th style="padding:2.5px;" rowspan="2">Quantity</th>_x000D_
        <th style="padding:2.5px;" colspan="2">Rate per Item</th>_x000D_
        <th style="padding:2.5px;" colspan="2">AMOUNT</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th>Rs.</th>_x000D_
        <th>P.</th>_x000D_
        <th>Rs.</th>_x000D_
        <th>P.</th>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

The view 'Index' or its master was not found.

The problem was that I used MvcRoute.MappUrl from MvcContrib to route the context.Routes.

It seems that MvcContrib routing mapper was uncomfortable with area routing.

When would you use the Builder Pattern?

I used builder in home-grown messaging library. The library core was receiving data from the wire, collecting it with Builder instance, then, once Builder decided it've got everything it needed to create a Message instance, Builder.GetMessage() was constructing a message instance using the data collected from the wire.