Programs & Examples On #Actionform

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

I had this problem and I realized I had not bound my component to a variable.

Changed

<input #myComponent="ngModel" />

to

<input #myComponent="ngModel" [(ngModel)]="myvar" />

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

its happen when you try to delete the same object and then again update the same object use this after delete

session.clear();

Import and insert sql.gz file into database with putty

The file is a gzipped (compressed) SQL file, almost certainly a plain text file with .sql as its extension. The first thing you need to do is copy the file to your database server via scp.. I think PuTTY's is pscp.exe

# Copy it to the server via pscp
C:\> pscp.exe numbers.sql.gz user@serverhostname:/home/user

Then SSH into your server and uncompress the file with gunzip

user@serverhostname$  gunzip numbers.sql.gz
user@serverhostname$  ls 

numbers.sql

Finally, import it into your MySQL database using the < input redirection operator:

user@serverhostname$  mysql -u mysqluser -p < numbers.sql

If the numbers.sql file doesn't create a database but expects one to be present already, you will need to include the database in the command as well:

user@serverhostname$  mysql -u mysqluser -p databasename < numbers.sql

If you have the ability to connect directly to your MySQL server from outside, then you could use a local MySQL client instead of having to copy and SSH. In that case, you would just need a utility that can decompress .gz files on Windows. I believe 7zip does so, or you can obtain the gzip/gunzip binaries for Windows.

Starting Docker as Daemon on Ubuntu

I had the same problem, and it was caused by line for insecured registry in: /etc/default/docker

sudo: port: command not found

I found the answer in the official website

$ vi ~/.profile

# add the following line
export PATH=/opt/local/bin:/opt/local/sbin:$PATH

And now restart the terminal or type source !$ (equivalent to source ~/.profile)

Convert nullable bool? to bool

If you're going to use the bool? in an if statement, I find the easiest thing to do is to compare against either true or false.

bool? b = ...;

if (b == true) { Debug.WriteLine("true"; }
if (b == false) { Debug.WriteLine("false"; }
if (b != true) { Debug.WriteLine("false or null"; }
if (b != false) { Debug.WriteLine("true or null"; }

Of course, you can also compare against null as well.

bool? b = ...;

if (b == null) { Debug.WriteLine("null"; }
if (b != null) { Debug.WriteLine("true or false"; }
if (b.HasValue) { Debug.WriteLine("true or false"; }
//HasValue and != null will ALWAYS return the same value, so use whatever you like.

If you're going to convert it to a bool to pass on to other parts of the application, then the Null Coalesce operator is what you want.

bool? b = ...;
bool b2 = b ?? true; // null becomes true
b2 = b ?? false; // null becomes false

If you've already checked for null, and you just want the value, then access the Value property.

bool? b = ...;
if(b == null)
    throw new ArgumentNullException();
else
    SomeFunc(b.Value);

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

Android: how to handle button click

Step 1:Create an XML File:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnClickEvent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />
</LinearLayout>

Step 2:Create MainActivity:

package com.scancode.acutesoft.telephonymanagerapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

    Button btnClickEvent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnClickEvent = (Button) findViewById(R.id.btnClickEvent);
        btnClickEvent.setOnClickListener(MainActivity.this);

    }

    @Override
    public void onClick(View v) {
        //Your Logic
    }
}

HappyCoding!

pandas dataframe columns scaling with sklearn

I know it's a very old comment, but still:

Instead of using single bracket (dfTest['A']), use double brackets (dfTest[['A']]).

i.e: min_max_scaler.fit_transform(dfTest[['A']]).

I believe this will give the desired result.

Styling mat-select in Angular Material

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

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

Demo


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

1. Use ::ng-deep:

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

CSS:

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

DEMO


2. Use ViewEncapsulation

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

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

Typscript:

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

CSS

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

DEMO


3. Set class style in style.css

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

style.css

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

DEMO


4. Use inline style

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

DEMO

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Instead of passing reference object passed the saved object, below is explanation which solve my issue:

//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)

//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)

symfony 2 No route found for "GET /"

Using symfony 2.3 with php 5.5 and using the built in server with

app/console server:run

which should output something like:

Server running on http://127.0.0.1:8000
Quit the server with CONTROL-C.

then go to http://127.0.0.1:8000/app_dev.php/app/example

this should give you the default, which you can also find the default route by viewing src/AppBundle/Controller/DefaultController.php

BULK INSERT with identity (auto-increment) column

I had a similar issue, but I needed to be sure that the order of the ID is aligning to the order in the source file. My solution is using a VIEW for the BULK INSERT:

Keep your table as it is and create this VIEW (select everything except the ID column)

CREATE VIEW [dbo].[VW_Employee]
AS
SELECT [Name], [Address]
FROM [dbo].[Employee];

Your BULK INSERT should then look like:

BULK INSERT [dbo].[VW_Employee] FROM 'path\tempFile.csv ' 
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');

using lodash .groupBy. how to add your own keys for grouped output?

You can do it like this in Lodash 4.x

_x000D_
_x000D_
var data = [{_x000D_
  "name": "jim",_x000D_
  "color": "blue",_x000D_
  "age": "22"_x000D_
}, {_x000D_
  "name": "Sam",_x000D_
  "color": "blue",_x000D_
  "age": "33"_x000D_
}, {_x000D_
  "name": "eddie",_x000D_
  "color": "green",_x000D_
  "age": "77"_x000D_
}];_x000D_
_x000D_
console.log(_x000D_
  _.chain(data)_x000D_
    // Group the elements of Array based on `color` property_x000D_
    .groupBy("color")_x000D_
    // `key` is group's name (color), `value` is the array of objects_x000D_
    .map((value, key) => ({ color: key, users: value }))_x000D_
    .value()_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


Original Answer

var result = _.chain(data)
    .groupBy("color")
    .pairs()
    .map(function(currentItem) {
        return _.object(_.zip(["color", "users"], currentItem));
    })
    .value();
console.log(result);

Online Demo

Note: Lodash 4.0 onwards, the .pairs function has been renamed to _.toPairs()

How to insert element into arrays at specific position?

easy way.. using array_splice()

$array_1 = array(
  '0' => 'zero',
  '1' => 'one',
  '2' => 'two',
  '3' => 'three',
);

$addArray = array('sample_key' => 'sample_value');

array_splice($rs, 3, 0, $addArray);

Result..

Array
(
    [0] => zero
    [1] => one
    [2] => two
    [3] => sample_value
    [4] => three
)

Inserting data into a MySQL table using VB.NET

You need to use ?param instead of @param when performing queries to MySQL

 str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
        sqlCommand.Connection = SQLConnection
        sqlCommand.CommandText = str_carSql
        sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
        sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
        sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
        sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
        sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
        sqlCommand.ExecuteNonQuery()

Change the catch block to see the actual exception:

  Catch ex As Exception
         MsgBox(ex.Message)   
          Return False

    End Try

Node JS Error: ENOENT

if your tmp folder is relative to the directory where your code is running remove the / in front of /tmp.

So you just have tmp/test.jpg in your code. This worked for me in a similar situation.

Jump into interface implementation in Eclipse IDE

Here's what I do:

  • In the interface, move the cursor to the method name. Press F4. => Type Hierarchy view appears
  • In the lower part of the view, the method should already be selected. In its toolbar, click "Lock view and show members in hierarchy" (should be the leftmost toolbar icon).
  • In the upper part of the view, you can browse through all implementations of the method.

The procedure isn't very quick, but it gives you a good overview.

How to name variables on the fly?

Use assign:

assign(paste("orca", i, sep = ""), list_name[[i]])

Overlapping Views in Android

Android handles transparency across views and drawables (including PNG images) natively, so the scenario you describe (a partially transparent ImageView in front of a Gallery) is certainly possible.

If you're having problems it may be related to either the layout or your image. I've replicated the layout you describe and successfully achieved the effect you're after. Here's the exact layout I used.

<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/gallerylayout"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Gallery
    android:id="@+id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
  <ImageView
    android:id="@+id/navigmaske"
    android:background="#0000"      
    android:src="@drawable/navigmask"
    android:scaleType="fitXY"
    android:layout_alignTop="@id/overview"
    android:layout_alignBottom="@id/overview"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  />
</RelativeLayout>

Note that I've changed the parent RelativeLayout to a height and width of fill_parent as is generally what you want for a main Activity. Then I've aligned the top and bottom of the ImageView to the top and bottom of the Gallery to ensure it's centered in front of it.

I've also explicitly set the background of the ImageView to be transparent.

As for the image drawable itself, if you put the PNG file somewhere for me to look at I can use it in my project and see if it's responsible.

"Could not get any response" response when using postman with subdomain

I just experienced this error. In my case, the path was TOO LONG. So url like that gave me this error in postman (fake example)

http://127.0.0.1:5000/api/batch/upload_import_deactivate_from_ready_folder

whereas

http://127.0.0.1:5000/api/batch/upld_impt_deac_ready_folder

worked fine.

Hope it helps someone who by accident read that far...

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

How to get the difference between two arrays of objects in JavaScript

If you are willing to use external libraries, You can use _.difference in underscore.js to achieve this. _.difference returns the values from array that are not present in the other arrays.

_.difference([1,2,3,4,5][1,4,10])

==>[2,3,5]

Is it possible to make desktop GUI application in .NET Core?

.NET Core 3 will have support for creating Windows desktop applications. I watched a demo of the technology yesterday during the .NET Conference.

This is the only blog post I could find, but it does illustrate the point: .NET Core 3 and Support for Windows Desktop Applications

Is there a way to ignore a single FindBugs warning?

As others Mentioned, you can use the @SuppressFBWarnings Annotation. If you don't want or can't add another Dependency to your code, you can add the Annotation to your Code yourself, Findbugs dosn't care in which Package the Annotation is.

@Retention(RetentionPolicy.CLASS)
public @interface SuppressFBWarnings {
    /**
     * The set of FindBugs warnings that are to be suppressed in
     * annotated element. The value can be a bug category, kind or pattern.
     *
     */
    String[] value() default {};

    /**
     * Optional documentation of the reason why the warning is suppressed
     */
    String justification() default "";
}

Source: https://sourceforge.net/p/findbugs/feature-requests/298/#5e88

Load text file as strings using numpy.loadtxt()

Use genfromtxt instead. It's a much more general method than loadtxt:

import numpy as np
print np.genfromtxt('col.txt',dtype='str')

Using the file col.txt:

foo bar
cat dog
man wine

This gives:

[['foo' 'bar']
 ['cat' 'dog']
 ['man' 'wine']]

If you expect that each row has the same number of columns, read the first row and set the attribute filling_values to fix any missing rows.

Equation for testing if a point is inside a circle

As said above -- use Euclidean distance.

from math import hypot

def in_radius(c_x, c_y, r, x, y):
    return math.hypot(c_x-x, c_y-y) <= r

Creating a very simple 1 username/password login in php

Firstly, you need to put session_start(); before any output to the browser, normally at the top of the page. Have a look at the manual.

Second, this won't affect your results, but these lines aren't being used anywhere and should be removed:

$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';

...and the last two lines there wouldn't work, you need to put the quotes inside the square brackets:

$username = $_POST['username'];

If you put session_start() at the top of your page (i.e. before the <html> tag etc), this should work fine.

Display HTML snippets in HTML

If your goal is to show a chunk of code that you're executing elsewhere on the same page, you can use textContent (it's pure-js and well supported: http://caniuse.com/#feat=textcontent)

<div id="myCode">
    <p>
        hello world
    </p>
</div>

<div id="loadHere"></div>


document.getElementById("myCode").textContent = document.getElementById("loadHere").innerHTML;

To get multi-line formatting in the result, you need to set css style "white-space: pre;" on the target div, and write the lines individually using "\r\n" at the end of each.

Here's a demo: https://jsfiddle.net/wphps3od/

This method has an advantage over using textarea: Code wont be reformatted as it would in a textarea. (Things like &nbsp; are removed entirely in a textarea)

Android check permission for LocationManager

The last part of the error message you quoted states: ...with ("checkPermission") or explicitly handle a potential "SecurityException"

A much quicker/simpler way of checking if you have permissions is to surround your code with try { ... } catch (SecurityException e) { [insert error handling code here] }. If you have permissions, the 'try' part will execute, if you don't, the 'catch' part will.

Is Java "pass-by-reference" or "pass-by-value"?

Java is always pass by value, not pass by reference

First of all, we need to understand what pass by value and pass by reference are.

Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.

Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.

Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:

public class PassByValue {
    public static void main(String[] args) {
        Test t = new Test();
        t.name = "initialvalue";
        new PassByValue().changeValue(t);
        System.out.println(t.name);
    }
    
    public void changeValue(Test f) {
        f.name = "changevalue";
    }
}

class Test {
    String name;
}

The output of this program is:

changevalue Let's understand step by step:

Test t = new Test(); As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .

first illustration

new PassByValue().changeValue(t);

When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.

second illustration

If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.

To understand this more clearly, consider the following example:

public class PassByValue {
    public static void main(String[] args) {
        Test t = new Test();
        t.name = "initialvalue";
        new PassByValue().changeRefence(t);
        System.out.println(t.name);
    }
    
    public void changeRefence(Test f) {
        f = null;
    }
}

class Test {
    String name;
}

Will this throw a NullPointerException? No, because it only passes a copy of the reference. In the case of passing by reference, it could have thrown a NullPointerException, as seen below:

third illustration

Hopefully this will help.

Allow docker container to connect to a local/host postgres database

Simple solution

Just add --network=host to docker run. That's all!

This way container will use the host's network, so localhost and 127.0.0.1 will point to the host (by default they point to a container). Example:

docker run -d --network=host \
  -e "DB_DBNAME=your_db" \
  -e "DB_PORT=5432" \
  -e "DB_USER=your_db_user" \
  -e "DB_PASS=your_db_password" \
  -e "DB_HOST=127.0.0.1" \
  --name foobar foo/bar

How to pass value from <option><select> to form action

with jQuery :
html :

<form method="POST" name="myform" action="index.php?action=contact_agent&agent_id="  onsubmit="SetData()">
  <select name="agent" id="agent">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
</form>

jQuery :

$('form').submit(function(){
   $(this).attr('action',$(this).attr('action')+$('#agent').val());
   $(this).submit();
});

javascript :

function SetData(){
   var select = document.getElementById('agent');
   var agent_id = select.options[select.selectedIndex].value;
   document.myform.action = "index.php?action=contact_agent&agent_id="+agent_id ; # or .getAttribute('action')
   myform.submit();
}

Summing elements in a list

You can also use reduce method:

>>> myList = [3, 5, 4, 9]
>>> myTotal = reduce(lambda x,y: x+y, myList)
>>> myTotal
21

Furthermore, you can modify the lambda function to do other operations on your list.

Use of True, False, and None as return values in Python functions

Concerning whether to raise an exception or return None: it depends on the use case. Either can be Pythonic.

Look at Python's dict class for example. x[y] hooks into dict.__getitem__, and it raises a KeyError if key is not present. But the dict.get method returns the second argument (which is defaulted to None) if key is not present. They are both useful.

The most important thing to consider is to document that behaviour in the docstring, and make sure that your get_attr() method does what it says it does.

To address your other questions, use these conventions:

if foo:
    # For testing truthiness

if not foo:
    # For testing falsiness

if foo is None:
    # Testing .. Noneliness ?

if foo is not None:
    # Check explicitly avoids common bugs caused by empty sequences being false

Functions that return True or False should probably have a name that makes this obvious to improve code readability:

def is_running_on_windows():
    return os.name == 'nt'

In Python 3 you can "type-hint" that:

>>> def is_running_on_windows() -> bool:
...     return os.name == 'nt'
... 
>>> is_running_on_windows.__annotations__
{'return': bool}

How to get back to most recent version in Git?

With Git 2.23+ (August 2019), the best practice would be to use git switch instead of the confusing git checkout command.

To create a new branch based on an older version:

git switch -c temp_branch HEAD~2

To go back to the current master branch:

git switch master

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

how to get all markers on google-maps-v3

If you are using JQuery Google map plug-in then below code will work for you -

var markers = $('#map_canvas').gmap('get','markers');

Centering a canvas

Tested only on Firefox:

<script>
window.onload = window.onresize = function() {
    var C = 0.8;        // canvas width to viewport width ratio
    var W_TO_H = 2/1;   // canvas width to canvas height ratio
    var el = document.getElementById("a");

    // For IE compatibility http://www.google.com/search?q=get+viewport+size+js
    var viewportWidth = window.innerWidth;
    var viewportHeight = window.innerHeight;

    var canvasWidth = viewportWidth * C;
    var canvasHeight = canvasWidth / W_TO_H;
    el.style.position = "fixed";
    el.setAttribute("width", canvasWidth);
    el.setAttribute("height", canvasHeight);
    el.style.top = (viewportHeight - canvasHeight) / 2;
    el.style.left = (viewportWidth - canvasWidth) / 2;

    window.ctx = el.getContext("2d");
    ctx.clearRect(0,0,canvasWidth,canvasHeight);
    ctx.fillStyle = 'yellow';
    ctx.moveTo(0, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, 0);
    ctx.lineTo(canvasWidth, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, canvasHeight);
    ctx.lineTo(0, canvasHeight/2);
    ctx.fill()
}
</script>

<body>
<canvas id="a" style="background: black">
</canvas>
</body>

PHP: How to remove specific element from an array?

$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}

install / uninstall APKs programmatically (PackageManager vs Intents)

API level 14 introduced two new actions: ACTION_INSTALL_PACKAGE and ACTION_UNINSTALL_PACKAGE. Those actions allow you to pass EXTRA_RETURN_RESULT boolean extra to get an (un)installation result notification.

Example code for invoking the uninstall dialog:

String app_pkg_name = "com.example.app";
int UNINSTALL_REQUEST_CODE = 1;

Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);  
intent.setData(Uri.parse("package:" + app_pkg_name));  
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, UNINSTALL_REQUEST_CODE);

And receive the notification in your Activity#onActivityResult method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == UNINSTALL_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Log.d("TAG", "onActivityResult: user accepted the (un)install");
        } else if (resultCode == RESULT_CANCELED) {
            Log.d("TAG", "onActivityResult: user canceled the (un)install");
        } else if (resultCode == RESULT_FIRST_USER) {
            Log.d("TAG", "onActivityResult: failed to (un)install");
        }
    }
}

When do you use Git rebase instead of Git merge?

Git rebase is used to make the branching paths in history cleaner and repository structure linear.

It is also used to keep the branches created by you private, as after rebasing and pushing the changes to the server, if you delete your branch, there will be no evidence of branch you have worked on. So your branch is now your local concern.

After doing rebase we also get rid of an extra commit which we used to see if we do a normal merge.

And yes, one still needs to do merge after a successful rebase as the rebase command just puts your work on top of the branch you mentioned during rebase, say master, and makes the first commit of your branch as a direct descendant of the master branch. This means we can now do a fast forward merge to bring changes from this branch to the master branch.

How to calculate the time interval between two time strings

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

Regarding to the question you still need to use datetime.strptime() as others said earlier.

How to turn a string formula into a "real" formula

Just for fun, I found an interesting article here, to use a somehow hidden evaluate function that does exist in Excel. The trick is to assign it to a name, and use the name in your cells, because EVALUATE() would give you an error msg if used directly in a cell. I tried and it works! You can use it with a relative name, if you want to copy accross rows if a sheet.

Which to use <div class="name"> or <div id="name">?

They do not do the same thing.id is used to target a specific element, classname can be used to target multiple elements.

Example:

<div id="mycolor1" class="mycolor2">     hello world </div>
<div class="mycolor2">     hello world2 </div>
<div class="mycolor2">     hello world3 </div>

Now, you can refer all the divs with classname mycolor2 at once using

.mycolor2{ color: red } //for example - in css

This would set all nodes with class mycolor2 to red.

However, if you want to set specifically mycolor1 to blue , you can target it specifically like this:

#mycolor1{ color: blue; }

GROUP BY and COUNT in PostgreSQL

Using OVER() and LIMIT 1:

SELECT COUNT(1) OVER()
FROM posts 
   INNER JOIN votes ON votes.post_id = posts.id 
GROUP BY posts.id
LIMIT 1;

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

Dynamically generating a QR code with PHP

I have been using google qrcode api for sometime, but I didn't quite like this because it requires me to be on the Internet to access the generated image.

I did a little comand-line research and found out that linux has a command line tool qrencode for generating qr-codes.

I wrote this little script. And the good part is that the generated image is less than 1KB in size. Well the supplied data is simply a url.

$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));

$imgData = "data:image/png;base64,".base64_encode($img);

Then in the html I load the image:

<img class="emrQRCode" src="<?=$imgData ?>" />

You just need to have installed it. [most imaging apps on linux would have installed it under the hood without you realizing.

How to break out of jQuery each Loop

To break a $.each or $(selector).each loop, you have to return false in the loop callback.

Returning true skips to the next iteration, equivalent to a continue in a normal loop.

$.each(array, function(key, value) { 
    if(value === "foo") {
        return false; // breaks
    }
});

// or

$(selector).each(function() {
  if (condition) {
    return false;
  }
});

Convert double to string

Try c.ToString("F6");

(For a full explanation of numeric formatting, see MSDN)

Requested registry access is not allowed

This issue has to do with granting the necessary authorization to the user account the application runs on. To read a similar situation and a detailed response for the correct solution, as documented by Microsoft, feel free to visit this post: http://rambletech.wordpress.com/2011/10/17/requested-registry-access-is-not-allowed/

python: restarting a loop

Changing the index variable i from within the loop is unlikely to do what you expect. You may need to use a while loop instead, and control the incrementing of the loop variable yourself. Each time around the for loop, i is reassigned with the next value from range(). So something like:

i = 2
while i < n:
    if(something):
        do something
    else:
        do something else
        i = 2 # restart the loop
        continue
    i += 1

In my example, the continue statement jumps back up to the top of the loop, skipping the i += 1 statement for that iteration. Otherwise, i is incremented as you would expect (same as the for loop).

Label points in geom_point

Instead of using the ifelse as in the above example, one can also prefilter the data prior to labeling based on some threshold values, this saves a lot of work for the plotting device:

xlimit <- 36
ylimit <- 24
ggplot(myData)+geom_point(aes(myX,myY))+
    geom_label(data=myData[myData$myX > xlimit & myData$myY> ylimit,], aes(myX,myY,myLabel))

How can I remove or replace SVG content?

I had two charts.

<div id="barChart"></div>
<div id="bubbleChart"></div>

This removed all charts.

d3.select("svg").remove(); 

This worked for removing the existing bar chart, but then I couldn't re-add the bar chart after

d3.select("#barChart").remove();

Tried this. It not only let me remove the existing bar chart, but also let me re-add a new bar chart.

d3.select("#barChart").select("svg").remove();

var svg = d3.select('#barChart')
       .append('svg')
       .attr('width', width + margins.left + margins.right)
       .attr('height', height + margins.top + margins.bottom)
       .append('g')
       .attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');

Not sure if this is the correct way to remove, and re-add a chart in d3. It worked in Chrome, but have not tested in IE.

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

C# - Create SQL Server table programmatically

Try this

Check if table have there , and drop the table , then create

using (SqlCommand command = new SqlCommand("IF EXISTS (
SELECT *
FROM sys.tables
WHERE name LIKE '#Customer%')
DROP TABLE #Customer CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))

How to dynamically create generic C# object using reflection?

Check out this article and this simple example. Quick translation of same to your classes ...

var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

Per your edit: For that case, you can do this ...

var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

To see where I came up with backtick1 for the name of the generic class, see this article.

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type type = typeof(IReadOnlyDictionary<,>);

How to reverse apply a stash?

How to reverse apply a stash?

Apart from what others have mentioned, easiest way is first do

git reset HEAD

and then checkout all local changes

git checkout . 

Filter dataframe rows if value in column is in a set list of values

you can also use ranges by using:

b = df[(df['a'] > 1) & (df['a'] < 5)]

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

How to check what user php is running as?

If available you can probe the current user account with posix_geteuid and then get the user name with posix_getpwuid.

$username = posix_getpwuid(posix_geteuid())['name'];

If you are running in safe mode however (which is often the case when exec is disabled), then it's unlikely that your PHP process is running under anything but the default www-data or apache account.

how to make log4j to write to the console as well

Write the root logger as below for logging on both console and FILE

log4j.rootLogger=ERROR,console,FILE

And write the respective definitions like Target, Layout, and ConversionPattern (MaxFileSize for file etc).

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

SQL Server - INNER JOIN WITH DISTINCT

add "distinct" after "select".

select distinct a.FirstName, a.LastName, v.District , v.LastName
from AddTbl a 
inner join ValTbl v  where a.LastName = v.LastName  order by Firstname

How to access the services from RESTful API in my angularjs page?

Welcome to the wonderful world of Angular !!

I am very new to angularJS. I am searching for accessing services from RESTful API but I didn't get any idea. please help me to do that. Thank you

There are two (very big) hurdles to writing your first Angular scripts, if you're currently using 'GET' services.

First, your services must implement the "Access-Control-Allow-Origin" property, otherwise the services will work a treat when called from, say, a web browser, but fail miserably when called from Angular.

So, you'll need to add a few lines to your web.config file:

<configuration>
  ... 
  <system.webServer>
    <httpErrors errorMode="Detailed"/>
    <validation validateIntegratedModeConfiguration="false"/>
    <!-- We need the following 6 lines, to let AngularJS call our REST web services -->
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*"/>
            <add name="Access-Control-Allow-Headers" value="Content-Type"/>
        </customHeaders>
    </httpProtocol>
  </system.webServer>
  ... 
</configuration>

Next, you need to add a little bit of code to your HTML file, to force Angular to call 'GET' web services:

// Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

Once you have these fixes in place, actually calling a RESTful API is really straightforward.

function YourAngularController($scope, $http) 
{
    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
        .success(function (data) {
        //  
        //  Do something with the data !
        //  
    });
}

You can find a really clear walkthrough of these steps on this webpage:

Using Angular, with JSON data

Good luck !

Mike

What are the alternatives now that the Google web search API has been deprecated?

You could just send them through like a browser does, and then parse the html, that is what I have always done, even for things like Youtube.

How to round up with excel VBA round()?

Here's one I made. It doesn't use a second variable, which I like.

        Points = Len(Cells(1, i)) * 1.2
        If Round(Points) >= Points Then
            Points = Round(Points)
        Else: Points = Round(Points) + 1
        End If

How to prevent caching of my Javascript file?

Configure your webserver to send caching control HTTP headers for the script.

Fake headers in the HTML documents:

  1. Aren't as well supported as real HTTP headers
  2. Apply to the HTML document, not to resources that it links to

Call a Vue.js component method from outside the component

A slightly different (simpler) version of the accepted answer:

Have a component registered on the parent instance:

export default {
    components: { 'my-component': myComponent }
}

Render the component in template/html with a reference:

<my-component ref="foo"></my-component>

Access the component method:

<script>
    this.$refs.foo.doSomething();
</script>

How do I add a tool tip to a span element?

In most browsers, the title attribute will render as a tooltip, and is generally flexible as to what sorts of elements it'll work with.

<span title="This will show as a tooltip">Mouse over for a tooltip!</span>
<a href="http://www.stackoverflow.com" title="Link to stackoverflow.com">stackoverflow.com</a>
<img src="something.png" alt="Something" title="Something">

All of those will render tooltips in most every browser.

converting a javascript string to a html object

var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

for (Integer i : l)
{
    if (i.intValue() == 5){
            itemsToRemove.add(i);
            break;
    }
}

The catch is the after removing the element from the list if you skip the internal iterator.next() call. it still works! Though I dont propose to write code like this it helps to understand the concept behind it :-)

Cheers!

How to filter an array of objects based on values in an inner array with jq?

Very close! In your select expression, you have to use a pipe (|) before contains.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key

E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].

When is JavaScript synchronous?

To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don't necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.

JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete etc...

The main point of confusion arises from the fact that your browser is able to tell JS to execute more code at anytime (similar to how you can execute more JS code on a page from the console). As an example JS has Callback functions who's purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.

Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)

I hope this is clear enough to be helpful to somebody.

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

Decimal separator comma (',') with numberDecimal inputType in EditText

I don't know why your answers are so complicated. If there's a bug in SDK you must override it or go around.

I have chosen the second way to solve that problem. If you format your string as Locale.ENGLISH and then put it to the EditText (even as an empty string). Example:

String.format(Locale.ENGLISH,"%.6f", yourFloatNumber);

Chasing that solution your result are compatible with the shown keyboard. Then float and double numbers work in typical for programming languages manner with dot instead of comma.

sweet-alert display HTML code in text

Sweet alerts also has an 'html' option, set it to true.

var hh = "<b>test</b>";
swal({
    title: "" + txt + "", 
    html: true,
    text: "Testno  sporocilo za objekt " + hh + "",  
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

Java: Multiple class declarations in one file

My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.

As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)

MySQL and PHP - insert NULL rather than empty string

This works just fine for me:

INSERT INTO table VALUES ('', NULLIF('$date',''))

(first '' increments id field)

Efficient way to apply multiple filters to pandas DataFrame or Series

Chaining conditions creates long lines, which are discouraged by pep8. Using the .query method forces to use strings, which is powerful but unpythonic and not very dynamic.

Once each of the filters is in place, one approach is

import numpy as np
import functools
def conjunction(*conditions):
    return functools.reduce(np.logical_and, conditions)

c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4

data_filtered = data[conjunction(c1,c2,c3)]

np.logical operates on and is fast, but does not take more than two arguments, which is handled by functools.reduce.

Note that this still has some redundancies: a) shortcutting does not happen on a global level b) Each of the individual conditions runs on the whole initial data. Still, I expect this to be efficient enough for many applications and it is very readable.

You can also make a disjunction (wherein only one of the conditions needs to be true) by using np.logical_or instead:

import numpy as np
import functools
def disjunction(*conditions):
    return functools.reduce(np.logical_or, conditions)

c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4

data_filtered = data[disjunction(c1,c2,c3)]

Count the number of times a string appears within a string

Probably not the most efficient, but think it's a neat way to do it.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true"));
        Console.WriteLine(CountAllTheTimesThisStringAppearsInThatString("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "false"));

    }

    static Int32 CountAllTheTimesThisStringAppearsInThatString(string orig, string find)
    {
        var s2 = orig.Replace(find,"");
        return (orig.Length - s2.Length) / find.Length;
    }
}

SQL Server - In clause with a declared variable

This is an example where I use the table variable to list multiple values in an IN clause. The obvious reason is to be able to change the list of values only one place in a long procedure.

To make it even more dynamic and alowing user input, I suggest declaring a varchar variable for the input, and then using a WHILE to loop trough the data in the variable and insert it into the table variable.

Replace @your_list, Your_table and the values with real stuff.

DECLARE @your_list TABLE (list varchar(25)) 
INSERT into @your_list
VALUES ('value1'),('value2376')

SELECT *  
FROM your_table 
WHERE your_column in ( select list from @your_list )

The select statement abowe will do the same as:

SELECT *  
FROM your_table 
WHERE your_column in ('value','value2376' )

How do you use NSAttributedString?

Since iOS 7 you can use NSAttributedString with HTML syntax:

NSURL *htmlString = [[NSBundle mainBundle]  URLForResource: @"string"     withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
                                                                                       options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
                                                                            documentAttributes:nil
                                                                                         error:nil];
textView.attributedText = stringWithHTMLAttributes;// you can use a label also

You have to add the file "string.html" to you project, and the content of the html can be like this:

<html>
  <head>
    <style type="text/css">
      body {
        font-size: 15px;
        font-family: Avenir, Arial, sans-serif;
      }
      .red {
        color: red;
      }
      .green {
        color: green;
      }
      .blue {
        color: blue;
      }
    </style>
  </head>
  <body>
    <span class="red">first</span><span class="green">second</span><span class="blue">third</span>
  </body>
</html>  

Now, you can use NSAttributedString as you want, even without HTML file, like for example:

//At the top of your .m file
#define RED_OCCURENCE -red_occurence-
#define GREEN_OCCURENCE -green_occurence-
#define BLUE_OCCURENCE -blue_occurence-
#define HTML_TEMPLATE @"<span style=\"color:red\">-red_occurence-</span><span style=\"color:green\">-green_occurence-</span><span style=\"color:blue\">-blue_occurence-</span></body></html>"

//Where you need to use your attributed string
NSString *string = [HTML_TEMPLATE stringByReplacingOccurrencesOfString:RED_OCCURENCE withString:@"first"] ;
string = [string stringByReplacingOccurrencesOfString:GREEN_OCCURENCE   withString:@"second"];
string = [string stringByReplacingOccurrencesOfString:BLUE_OCCURENCE    withString:@"third"];

NSData* cData = [string dataUsingEncoding:NSUTF8StringEncoding];

NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithData:cData
                                                                                options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
                                                                        documentAttributes:nil
                                                                                     error:nil];
textView.attributedText = stringWithHTMLAttributes;

Source

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

Overriding !important style

There we have another possibility to remove a property value from the CSS.

Like using the replace method in js. But you have to know exactly the ID of the style, or you can write a for loop to detecting that by (count styles on the page, then check if any of those 'includes' or 'match' an !important value. & you can count also - how much contains them, or just simply write a global [regexp: /str/gi] replacing method)

Mine is very simple, but I attach a jsBin, for example:

https://jsbin.com/geqodeg/edit?html,css,js,output

First I set the body background in CSS for yellow !important, then I overrided by JS for darkPink.

check if "it's a number" function in Oracle

Saish's answer using REGEXP_LIKE is the right idea but does not support floating numbers. This one will ...

Return values that are numeric

SELECT  foo 
FROM    bar
WHERE   REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');

Return values not numeric

SELECT  foo 
FROM    bar
WHERE   NOT REGEXP_LIKE (foo,'^-?\d+(\.\d+)?$');

You can test your regular expressions themselves till your heart is content at http://regexpal.com/ (but make sure you select the checkbox match at line breaks for this one).

Attach a body onload event with JS

Why not using jQuery?

$(document).ready(function(){}))

As far as I know, this is the perfect solution.

postgresql COUNT(DISTINCT ...) very slow

You can use this:

SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;

This is much faster than:

COUNT(DISTINCT column_name)

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

What is the maximum length of a valid email address?

320

And the segments look like this

{64}@{255}

64 + 1 + 255 = 320

You should also read this if you are validating emails

http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

jQuery delete all table rows except first

wrapped in a function:

function remove_rows(tablename) { 
    $(tablename).find("tr:gt(0)").remove();        
}

then call it:

remove_rows('#table1');
remove_rows('#table2');

joining two select statements

This will do what you want:

select * 
  from orders_products 
       INNER JOIN orders 
          ON orders_products.orders_id = orders.orders_id
 where products_id in (180, 181);

Check if a number has a decimal place/is a whole number

//How about byte-ing it?

Number.prototype.isInt= function(){
 return this== this>> 0;
}

I always feel kind of bad for bit operators in javascript-

they hardly get any exercise.

Get the client's IP address in socket.io

I have found that within the socket.handshake.headers there is a forwarded for address which doesn't appear on my local machine. And I was able to get the remote address using:

socket.handshake.headers['x-forwarded-for']

This is in the server side and not client side.

How to use radio on change event?

A simpler and cleaner way would be to use a class with @Ohgodwhy's answer

<input ... class="rButton">
<input ... class="rButton">

Script

?$( ".rButton" ).change(function() {
    switch($(this).val()) {
        case 'allot' :
            alert("Allot Thai Gayo Bhai");
            break;
        case 'transfer' :
            alert("Transfer Thai Gayo");
            break;
    }            
});?

What is a pre-revprop-change hook in SVN, and how do I create it?

The name of the hook script is not so scary if you manage decipher it: it's pre revision property change hook. In short, the purpose of pre-revprop-change hook script is to control changes of unversioned (revision) properties and to send notifications (e.g. to send an email when revision property is changed).

There are 2 types of properties in Subversion:

  • versioned properties (e.g svn:needs-lock and svn:mime-type) that can be set on files and directories,
  • unversioned (revision) properties (e.g. svn:log and svn:date) that are set on repository revisions.

Versioned properties have history and can be manipulated by ordinary users who have Read / Write access to a repository. On the other hand, unversioned properties do not have any history and serve mostly maintenance purpose. For example, if you commit a revision it immediately gets svn:date with UTC time of your commit, svn:author with your username and svn:log with your commit log message (if you specified any).

As I already specified, the purpose of pre-revprop-change hook script is to control changes of revision properties. You don't want everyone who has access to a repository to be able to modify all revision properties, so changing revision properties is forbidden by default. To allow users to change properties, you have to create pre-revprop-change hook.

The simplest hook can contain just one line: exit 0. It will allow any authenticated user to change any revision property and it should not be used in real environment. On Windows, you can use batch script or PowerShell-based script to implement some logic within pre-revprop-change hook.

This PowerShell script allows to change svn:log property only and denies empty log messages.

# Store hook arguments into variables with mnemonic names
$repos    = $args[0]
$rev      = $args[1]
$user     = $args[2]
$propname = $args[3]
$action   = $args[4]

# Only allow changes to svn:log. The author, date and other revision
# properties cannot be changed
if ($propname -ne "svn:log")
{
  [Console]::Error.WriteLine("Only changes to 'svn:log' revision properties are allowed.")
  exit 1
}

# Only allow modifications to svn:log (no addition/overwrite or deletion)
if ($action -ne "M")
{
  [Console]::Error.WriteLine("Only modifications to 'svn:log' revision properties are allowed.")
  exit 2
}

# Read from the standard input while the first non-white-space characters
$datalines = ($input | where {$_.trim() -ne ""})
if ($datalines.length -lt 25)
{
  # Log message is empty. Show the error.
  [Console]::Error.WriteLine("Empty 'svn:log' properties are not allowed.")
  exit 3
}

exit 0

This batch script allows only "svnmgr" user to change revision properties:

IF "%3" == "svnmgr" (goto :label1) else (echo "Only the svnmgr user may change revision properties" >&2 )

exit 1
goto :eof

:label1
exit 0

In Objective-C, how do I test the object type?

When you want to differ between a superClass and the inheritedClass you can use:

if([myTestClass class] == [myInheritedClass class]){
   NSLog(@"I'm the inheritedClass);
} 
if([myTestClass class] == [mySuperClass class]){
   NSLog(@"I'm the superClass);
} 

Using - (BOOL)isKindOfClass:(Class)aClass in this case would result in TRUE both times because the inheritedClass is also a kind of the superClass.

Close Form Button Event

Apply the below code where you want to make code to exit application.

System.Windows.Forms.Application.Exit( )

Trigger insert old values- values that was updated

In SQL Server 2008 you can use Change Data Capture for this. Details of how to set it up on a table are here http://msdn.microsoft.com/en-us/library/cc627369.aspx

Generating a list of pages (not posts) without the index file

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

docker: "build" requires 1 argument. See 'docker build --help'

In my case this error was happening in a Gitlab CI pipeline when I was passing multiple Gitlab env variables to docker build with --build-arg flags.

Turns out that one of the variables had a space in it which was causing the error. It was difficult to find since the pipeline logs just showed the $VARIABLE_NAME.

Make sure to quote the environment variables so that spaces get handled correctly.

Change from:

--build-arg VARIABLE_NAME=$VARIABLE_NAME

to:

--build-arg VARIABLE_NAME="$VARIABLE_NAME"

The following untracked working tree files would be overwritten by merge, but I don't care

Update - a better version

This tool (https://github.com/mklepaczewski/git-clean-before-merge) will:

  • delete untracked files that are identical to their git pull equivalents,
  • revert changes to modified files who's modified version is identical to their git pull equivalents,
  • report modified/untracked files that differ from their git pull version,
  • the tool has the --pretend option that will not modify any files.

Old version

How this answer differ from other answers?

The method presented here removes only files that would be overwritten by merge. If you have other untracked (possibly ignored) files in the directory this method won't remove them.

The solution

This snippet will extract all untracked files that would be overwritten by git pull and delete them.

git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} rm -rf "{}"

and then just do:

git pull

This is not git porcelain command so always double check what it would do with:

git pull 2>&1|grep -E '^\s'|cut -f2-|xargs -I {} echo "{}"

Explanation - because one liners are scary:

Here's a breakdown of what it does:

  1. git pull 2>&1 - capture git pull output and redirect it all to stdout so we can easily capture it with grep.
  2. grep -E '^\s - the intent is to capture the list of the untracked files that would be overwritten by git pull. The filenames have a bunch of whitespace characters in front of them so we utilize it to get them.
  3. cut -f2- - remove whitespace from the beginning of each line captured in 2.
  4. xargs -I {} rm -rf "{}" - us xargs to iterate over all files, save their name in "{}" and call rm for each of them. We use -rf to force delete and remove untracked directories.

It would be great to replace steps 1-3 with porcelain command, but I'm not aware of any equivalent.

How do I show the changes which have been staged?

If you'd be interested in a visual side-by-side view, the diffuse visual diff tool can do that. It will even show three panes if some but not all changes are staged. In the case of conflicts, there will even be four panes.

Screenshot of diffuse with staged and unstaged edits

Invoke it with

diffuse -m

in your Git working copy.

If you ask me, the best visual differ I've seen for a decade. Also, it is not specific to Git: It interoperates with a plethora of other VCS, including SVN, Mercurial, Bazaar, ...

See also: Show both staged & working tree in git diff?

Get host domain from URL?

Try this

Console.WriteLine(GetDomain.GetDomainFromUrl("http://support.domain.com/default.aspx?id=12345"));

It will output support.domain.com

Or try

Uri.GetLeftPart( UriPartial.Authority )

Argument of type 'X' is not assignable to parameter of type 'X'

Also adding other Scenarios where you may see these Errors

  1. First Check you compiler version, Download latest Typescript compiler to support ES6 syntaxes

  2. typescript still produces output even with typing errors this doesn't actually block development,

When you see these errors Check for Syntaxes in initialization or when Calling these methods or variables,
Check whether the parameters of the functions are of wrong data Type,you initialized as 'string' and assigning a 'boolean' or 'number'

For Example

1.

 private errors: string;
    //somewhere in code you assign a boolean value to (string)'errors'
    this.errors=true
    or 
    this.error=5

2.

 private values: Array<number>;    
    this.values.push(value);  //Argument of type 'X' is not assignable to parameter of type 'X'

The Error message here is because the Square brackets for Array Initialization is missing, It works even without it, but VS Code red alerts.

private values: Array<number> = [];    
this.values.push(value);

Note:
Remember that Javascript typecasts according to the value assigned, So typescript notifies them but the code executes even with these errors highlighted in VS Code

Ex:

 var a=2;
 typeof(a) // "number"
 var a='Ignatius';
 typeof(a) // "string"

use jQuery to get values of selected checkboxes

Source - More Detail

Get Selected Checkboxes Value Using jQuery

Then we write jQuery script to get selected checkbox value in an array using jQuery each(). Using this jQuery function it runs a loop to get the checked value and put it into an array.

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Get Selected Checkboxes Value Using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".btn").click(function() {
                var locationthemes = [];
                $.each($("input[name='locationthemes']:checked"), function() {
                    locationthemes.push($(this).val());
                });
                alert("My location themes colors are: " + locationthemes.join(", "));
            });
        });
    </script>
    </head>
    <body>
        <form method="POST">
        <h3>Select your location themes:</h3>
        <input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
        <label for="checkbox-1">Castle</label>
        <input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
        <label for="checkbox-2">Barn</label>
        <input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" />
        <label for="checkbox-3">Restaurant</label>
        <input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" />
        <label for="checkbox-4">Bar</label>
        <br>
        <button type="button" class="btn">Get Values</button>
    </form>
    </body>
    </html>

Importing a function from a class in another file?

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose(a):
  from random import randint
  b = randint(0, len(a) - 1)
  c = a[b]
  return(c)

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

UML class diagram enum

They are simply showed like this:

_______________________
|   <<enumeration>>   |
|    DaysOfTheWeek    |
|_____________________|
| Sunday              |
| Monday              |
| Tuesday             |
| ...                 |
|_____________________|

And then just have an association between that and your class.

What is cardinality in Databases?

Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set

What's the difference between git reset --mixed, --soft, and --hard?

mkarasek's Answer is great, in simple terms we can say...

  • git reset --soft : set the HEAD to the intended commit but keep your changes staged from last commits
  • git reset --mixed : it's same as git reset --soft but the only difference is it un stage your changes from last commits
  • git reset --hard : set your HEAD on the commit you specify and reset all your changes from last commits including un committed changes.

Optional Parameters in Go?

Neither optional parameters nor function overloading are supported in Go. Go does support a variable number of parameters: Passing arguments to ... parameters

Mongoose query where value is not null

I ended up here and my issue was that I was querying for

{$not: {email: /@domain.com/}}

instead of

{email: {$not: /@domain.com/}}

Find duplicate entries in a column

Using:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

...will show you the ctn_no value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
   WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

If you want to see the other column values associated with the duplicate, you'll want to use a self join:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.ctn_no
          FROM YOUR_TABLE t
      GROUP BY t.ctn_no
        HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no

How to go to each directory and execute a command?

If you're using GNU find, you can try -execdir parameter, e.g.:

find . -type d -execdir realpath "{}" ';'

or (as per @gniourf_gniourf comment):

find . -type d -execdir sh -c 'printf "%s/%s\n" "$PWD" "$0"' {} \;

Note: You can use ${0#./} instead of $0 to fix ./ in the front.

or more practical example:

find . -name .git -type d -execdir git pull -v ';'

If you want to include the current directory, it's even simpler by using -exec:

find . -type d -exec sh -c 'cd -P -- "{}" && pwd -P' \;

or using xargs:

find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'

Or similar example suggested by @gniourf_gniourf:

find . -type d -print0 | while IFS= read -r -d '' file; do
# ...
done

The above examples support directories with spaces in their name.


Or by assigning into bash array:

dirs=($(find . -type d))
for dir in "${dirs[@]}"; do
  cd "$dir"
  echo $PWD
done

Change . to your specific folder name. If you don't need to run recursively, you can use: dirs=(*) instead. The above example doesn't support directories with spaces in the name.

So as @gniourf_gniourf suggested, the only proper way to put the output of find in an array without using an explicit loop will be available in Bash 4.4 with:

mapfile -t -d '' dirs < <(find . -type d -print0)

Or not a recommended way (which involves parsing of ls):

ls -d */ | awk '{print $NF}' | xargs -n1 sh -c 'cd $0 && pwd && echo Do stuff'

The above example would ignore the current dir (as requested by OP), but it'll break on names with the spaces.

See also:

Regex match everything after question mark?

With the positive lookbehind technique:

(?<=\?).*

(We're searching for a text preceded by a question mark here)

Input: derpderp?mystring blahbeh
Output: mystring blahbeh

Example

Basically the ?<= is a group construct, that requires the escaped question-mark, before any match can be made.

They perform really well, but not all implementations support them.

How to pass optional arguments to a method in C++?

With the introduction of std::optional in C++17 you can pass optional arguments:

#include <iostream>
#include <string>
#include <optional>

void myfunc(const std::string& id, const std::optional<std::string>& param = std::nullopt)
{
    std::cout << "id=" << id << ", param=";

    if (param)
        std::cout << *param << std::endl;
    else
        std::cout << "<parameter not set>" << std::endl;
}

int main() 
{
    myfunc("first");
    myfunc("second" , "something");
}

Output:

id=first param=<parameter not set>
id=second param=something

See https://en.cppreference.com/w/cpp/utility/optional

How to convert object array to string array in Java

Another alternative to System.arraycopy:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

Dynamically load a JavaScript file

If you want a SYNC script loading, you need to add script text directly to HTML HEAD tag. Adding it as will trigger an ASYNC load. To load script text from external file synchronously, use XHR. Below a quick sample (it is using parts of other answers in this and other posts):

/*sample requires an additional method for array prototype:*/

if (Array.prototype.contains === undefined) {
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) { if (this[i] === obj) return true; }
    return false;
};
};

/*define object that will wrap our logic*/
var ScriptLoader = {
LoadedFiles: [],

LoadFile: function (url) {
    var self = this;
    if (this.LoadedFiles.contains(url)) return;

    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                self.LoadedFiles.push(url);
                self.AddScript(xhr.responseText);
            } else {
                if (console) console.error(xhr.statusText);
            }
        }
    };
    xhr.open("GET", url, false);/*last parameter defines if call is async or not*/
    xhr.send(null);
},

AddScript: function (code) {
    var oNew = document.createElement("script");
    oNew.type = "text/javascript";
    oNew.textContent = code;
    document.getElementsByTagName("head")[0].appendChild(oNew);
}
};

/*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/

ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
ScriptLoader.LoadFile("Scripts/jquery-2.0.1.min.js");
/*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id "tb1"*/
$(function () { alert($('#tb1').val()); });

How to "test" NoneType in python?

I hope this example will be helpful for you)

print(type(None))  # NoneType

So, you can check type of the variable name

# Example
name = 12  # name = None

if type(name) is type(None):
    print("Can't find name")
else:
    print(name)

Distinct() with lambda?

Here's how you can do it:

public static class Extensions
{
    public static IEnumerable<T> MyDistinct<T, V>(this IEnumerable<T> query,
                                                    Func<T, V> f, 
                                                    Func<IGrouping<V,T>,T> h=null)
    {
        if (h==null) h=(x => x.First());
        return query.GroupBy(f).Select(h);
    }
}

This method allows you to use it by specifying one parameter like .MyDistinct(d => d.Name), but it also allows you to specify a having condition as a second parameter like so:

var myQuery = (from x in _myObject select x).MyDistinct(d => d.Name,
        x => x.FirstOrDefault(y=>y.Name.Contains("1") || y.Name.Contains("2"))
        );

N.B. This would also allow you to specify other functions like for example .LastOrDefault(...) as well.


If you want to expose just the condition, you can have it even simpler by implementing it as:

public static IEnumerable<T> MyDistinct2<T, V>(this IEnumerable<T> query,
                                                Func<T, V> f,
                                                Func<T,bool> h=null
                                                )
{
    if (h == null) h = (y => true);
    return query.GroupBy(f).Select(x=>x.FirstOrDefault(h));
}

In this case, the query would just look like:

var myQuery2 = (from x in _myObject select x).MyDistinct2(d => d.Name,
                    y => y.Name.Contains("1") || y.Name.Contains("2")
                    );

N.B. Here, the expression is simpler, but note .MyDistinct2 uses .FirstOrDefault(...) implicitly.


Note: The examples above are using the following demo class

class MyObject
{
    public string Name;
    public string Code;
}

private MyObject[] _myObject = {
    new MyObject() { Name = "Test1", Code = "T"},
    new MyObject() { Name = "Test2", Code = "Q"},
    new MyObject() { Name = "Test2", Code = "T"},
    new MyObject() { Name = "Test5", Code = "Q"}
};

@font-face not working

try to put below html in head tag.It worked for me.

 <title>ABC</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

HTML 5 input type="number" element for floating point numbers on Chrome

Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}" on the html input.

The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.

Does Index of Array Exist

// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:

int index = 25;

if (index >= 0 && index < array.Length)
{
    // Array element found
}

Java equivalent to #region in C#

AndroidStudio region
Create region

First, find (and define short cut if need) for Surround With menu enter image description here

Then, select the code, press Ctrl+Alt+Semicolon -> choose region..endregion...
enter image description here

Go to region

First, find Custom Folding short cut
enter image description here Second, from anywhere in your code, press Ctrl+Alt+Period('>' on keyboard) enter image description here

"Cannot allocate an object of abstract type" error

You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.

Download multiple files as a zip-file using php

This is a working example of making ZIPs in PHP:

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  if(file_exists($path)){
  $zip->addFromString(basename($path),  file_get_contents($path));  
  }
  else{
   echo"file does not exist";
  }
}
$zip->close();

Must declare the scalar variable

This is most likely not an answer to the issue itself but this question pops up as first result when searching for Sql declare scalar variable hence i share a possible solution to this error.

In my case this error was caused by the use of ; after a SQL statement. Just remove it and the error will be gone.

I guess the cause is the same as @IronSean already posted in an comment above:

it's worth noting that using GO (or in this case ;) causes a new branch where declared variables aren't visible past the statement.

For example:

DECLARE @id int
SET @id = 78

SELECT * FROM MyTable WHERE Id = @var; <-- remove this character to avoid the error message
SELECT * FROM AnotherTable WHERE MyTableId = @var

C# with MySQL INSERT parameters

I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.

The following code works lately:

string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";

using (MySqlConnection cn = new MySqlConnection(connetionString))
{
    try
    {
        string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
        cn.Open();
        using (MySqlCommand cmd = new MySqlCommand(query, cn))
        {
            cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
            cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
            cmd.ExecuteNonQuery();
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
    }
}

Check whether a value exists in JSON object

This example puts your JSON into proper format and does an existence check. I use jquery for convenience.

http://jsfiddle.net/nXFxC/

<!-- HTML -->
<span id="test">Hello</span><br>
<span id="test2">Hello</span>

//Javascript

$(document).ready(function(){
    var JSON = {"animals":[{"name":"cat"}, {"name":"dog"}]};

if(JSON.animals[1].name){      
$("#test").html("It exists");
}
if(!JSON.animals[2]){       
$("#test2").html("It doesn't exist");
}
});

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
    position:relative;
    width:80%;
    height:auto;
    overflow:auto;
}
#header {
    width:80%;
    height:50px;
    padding:10px;
}

Regex expressions in Java, \\s vs. \\s+

The first regex will match one whitespace character. The second regex will reluctantly match one or more whitespace characters. For most purposes, these two regexes are very similar, except in the second case, the regex can match more of the string, if it prevents the regex match from failing.  from http://www.coderanch.com/t/570917/java/java/regex-difference

Calling JMX MBean method from a shell script

The following command line JMX utilities are available:

  1. jmxterm - seems to be the most fully featured utility.
  2. cmdline-jmxclient - used in the WebArchive project seems very bare bones (and no development since 2006 it looks like)
  3. Groovy script and JMX - provides some really powerful JMX functionality but requires groovy and other library setup.
  4. JManage command line functionality - (downside is that it requires a running JManage server to proxy commands through)

Groovy JMX Example:

import java.lang.management.*
import javax.management.ObjectName
import javax.management.remote.JMXConnectorFactory as JmxFactory
import javax.management.remote.JMXServiceURL as JmxUrl

def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:9003/jmxrmi'
String beanName = "com.webwars.gameplatform.data:type=udmdataloadsystem,id=0"
def server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection
def dataSystem = new GroovyMBean(server, beanName)

println "Connected to:\n$dataSystem\n"

println "Executing jmxForceRefresh()"
dataSystem.jmxForceRefresh();

cmdline-jmxclient example:

If you have an

  • MBean: com.company.data:type=datasystem,id=0

With an Operation called:

  • jmxForceRefresh()

Then you can write a simple bash script (assuming you download cmdline-jmxclient-0.10.3.jar and put in the same directory as your script):

#!/bin/bash

cmdLineJMXJar=./cmdline-jmxclient-0.10.3.jar
user=yourUser
password=yourPassword
jmxHost=localhost
port=9003

#No User and password so pass '-'
echo "Available Operations for com.company.data:type=datasystem,id=0"
java -jar ${cmdLineJMXJar} ${user}:${password} ${jmxHost}:${port} com.company.data:type=datasystem,id=0

echo "Executing XML update..."
java -jar ${cmdLineJMXJar} - ${jmxHost}:${port} com.company.data:type=datasystem,id=0 jmxForceRefresh

Find the unique values in a column and then sort them

Came across the question myself today. I think the reason that your code returns 'None' (exactly what I got by using the same method) is that

a.sort()

is calling the sort function to mutate the list a. In my understanding, this is a modification command. To see the result you have to use print(a).

My solution, as I tried to keep everything in pandas:

pd.Series(df['A'].unique()).sort_values()

How do I format date and time on ssrs report?

If you want date and time separate then use below expressions: Date and Time Expression

Expression1 for current date : =formatdatetime(today) its return date is = 11/15/2016

Expression2 for current time : =CDate(Now).ToString("hh:mm tt") its return time is = 3:44 PM

This report printed on Expression1 at Expression2

Output will be : Output of Both Expression

This report printed on 11/15/2016 at 3:44 PM

How to get a jqGrid selected row cells value

You can use in this manner also

var rowId =$("#list").jqGrid('getGridParam','selrow');  
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId'];   // perticuler Column name of jqgrid that you want to access

jQuery find events handlers registered with an object

For jQuery 1.8+, this will no longer work because the internal data is placed in a different object.

The latest unofficial (but works in previous versions as well, at least in 1.7.2) way of doing it now is - $._data(element, "events")

The underscore ("_") is what makes the difference here. Internally, it is calling $.data(element, name, null, true), the last (fourth) parameter is an internal one ("pvt").

How to get current language code with Swift?

In Swift 3

let langStr = Locale.current.languageCode

jQuery ajax upload file in asp.net mvc

I have a sample like this on vuejs version: v2.5.2

<form action="url" method="post" enctype="multipart/form-data">
    <div class="col-md-6">
        <input type="file" class="image_0" name="FilesFront" ref="FilesFront" />
    </div>
    <div class="col-md-6">
        <input type="file" class="image_1" name="FilesBack" ref="FilesBack" />
    </div>
</form>
<script>
Vue.component('v-bl-document', {
    template: '#document-item-template',
    props: ['doc'],
    data: function () {
        return {
            document: this.doc
        };
    },
    methods: {
        submit: function () {
            event.preventDefault();

            var data = new FormData();
            var _doc = this.document;
            Object.keys(_doc).forEach(function (key) {
                data.append(key, _doc[key]);
            });
            var _refs = this.$refs;
            Object.keys(_refs).forEach(function (key) {
                data.append(key, _refs[key].files[0]);
            });

            debugger;
            $.ajax({
                type: "POST",
                data: data,
                url: url,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    //do something
                },

            });
        }
    }
});
</script>

Rename a column in MySQL

for mysql version 5

alter table *table_name* change column *old_column_name* *new_column_name* datatype();

When to use CouchDB over MongoDB and vice versa

Ask this questions yourself? And you will decide your DB selection.

  1. Do you need master-master? Then CouchDB. Mainly CouchDB supports master-master replication which anticipates nodes being disconnected for long periods of time. MongoDB would not do well in that environment.
  2. Do you need MAXIMUM R/W throughput? Then MongoDB
  3. Do you need ultimate single-server durability because you are only going to have a single DB server? Then CouchDB.
  4. Are you storing a MASSIVE data set that needs sharding while maintaining insane throughput? Then MongoDB.
  5. Do you need strong consistency of data? Then MongoDB.
  6. Do you need high availability of database? Then CouchDB.
  7. Are you hoping multi databases and multi tables/ collections? Then MongoDB
  8. You have a mobile app offline users and want to sync their activity data to a server? Then you need CouchDB.
  9. Do you need large variety of querying engine? Then MongoDB
  10. Do you need large community to be using DB? Then MongoDB

How do I configure git to ignore some files locally?

In order to ignore untracked files especially if they are located in (a few) folders that are not tracked, a simple solution is to add a .gitignore file to every untracked folder and enter in a single line containing * followed by a new line. It's a really simple and straightforward solution if the untracked files are in a few folders. For me, all files were coming from a single untracked folder vendor and the above just worked.

Generate a UUID on iOS from Swift

For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.

Inserting data into a temporary table

My way of Insert in SQL Server. Also I usually check if a temporary table exists.

IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP Table #MyTable

SELECT b.Val as 'bVals'
  INTO #MyTable
FROM OtherTable as b

Reverse engineering from an APK file to a project

If you are looking for a professional alternative, have a look at JEB Decompiler from PNF Software.

There is a demo version that will let you decompile most code.

How do I start an activity from within a Fragment?

Use the Base Context of the Activity in which your fragment resides to start an Intent.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

where fBaseCtx is BaseContext of your current activity. You can get it as fBaseCtx = getBaseContext();

Convert integer to binary in C#

http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html

    public string DecimalToBinary(string data)
    {
        string result = string.Empty;
        int rem = 0;
        try
        {
            if (!IsNumeric(data))
                error = "Invalid Value - This is not a numeric value";
            else
            {
                int num = int.Parse(data);
                while (num > 0)
                {
                    rem = num % 2;
                    num = num / 2;
                    result = rem.ToString() + result;
                }
            }
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        return result;
    }

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

You also could just throw new HttpMessageNotReadableException("error description") to benefit from Spring's default error handling.

However, just as is the case with those default errors, no response body will be set.

I find these useful when rejecting requests that could reasonably only have been handcrafted, potentially indicating a malevolent intent, since they obscure the fact that the request was rejected based on a deeper, custom validation and its criteria.

Hth, dtk

How do I add an active class to a Link from React Router?

On the Link component you can now add activeClassName or set activeStyle.

These allow you to easily add styles to the currently active link.


Previously, you could create a custom component that works like a wrapper to Link with the following logic.

In a file called nav_link.js

import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

class NavLink extends React.Component {
    render() {
        var isActive = this.context.router.route.location.pathname === this.props.to;
        var className = isActive ? 'active' : '';

        return(
            <Link className={className} {...this.props}>
                {this.props.children}
            </Link>
        );
    }
}

NavLink.contextTypes = {
    router: PropTypes.object
};

export default NavLink;

And use it as given below in your component:

...
import NavLink from "./nav_link";
.....

<nav>
    <ul className="nav nav-pills pull-right">
        <NavLink to="/">
            <i className="glyphicon glyphicon-home"></i> <span>Home</span>
        </NavLink>
        <NavLink to="about">
            <i className="glyphicon glyphicon-camera"></i> <span>About</span>
        </NavLink>
    </ul>
</nav>

Find indices of elements equal to zero in a NumPy array

import numpy as np

x = np.array([1,0,2,3,6])
non_zero_arr = np.extract(x>0,x)

min_index = np.amin(non_zero_arr)
min_value = np.argmin(non_zero_arr)

Scanner method to get a char

Scanner sc = new Scanner (System.in)
char c = sc.next().trim().charAt(0);

Reloading/refreshing Kendo Grid

$("#theidofthegrid").data("kendoGrid").dataSource.data([ ]);

MySQL: How to reset or change the MySQL root password?

This solution belongs to the previous version of MySQL. By logging in to MySQL using socket authentication, you can do it.

sudo mysql -u root

Then the following command could be run.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

Details are available here .

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

Ruby array to string conversion

array.inspect.inspect.gsub(/\[|\]/, "") could do the trick

How to check the first character in a string in Bash or UNIX shell?

cut -c1

This is POSIX, and unlike case actually extracts the first char if you need it for later:

myvar=abc
first_char="$(printf '%s' "$myvar" | cut -c1)"
if [ "$first_char" = a ]; then
  echo 'starts with a'
else
  echo 'does not start with a'
fi

awk substr is another POSIX but less efficient alternative:

printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'

printf '%s' is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:

myvar='\n'
printf '%s' "$myvar" | cut -c1

outputs \ as expected.

${::} does not seem to be POSIX.

See also: How to extract the first two characters of a string in shell scripting?

Get The Current Domain Name With Javascript (Not the path, etc.)

What about this function?

window.location.hostname.match(/\w*\.\w*$/gi)[0]

This will match only the domain name regardless if its a subdomain or a main domain

Node.js version on the command line? (not the REPL)

If you are windows user and using command line to check following versions then:

  1. Check node version

    node -v

  2. Check npm version

    npm -v

How to link to part of the same document in Markdown?

Experimenting, I found a solution using <div…/> but an obvious solution is to place your own anchor point in the page wherever you like, thus:

<a name="abcde">

before and

</a>

after the line you want to "link" to. Then a markdown link like:

[link text](#abcde)

anywhere in the document takes you there.

The <div…/> solution inserts a "dummy" division just to add the id property, and this is potentially disruptive to the page structure, but the <a name="abcde"/> solution ought to be quite innocuous.

(PS: It might be OK to put the anchor in the line you wish to link to, as follows:

## <a name="head1">Heading One</a>

but this depends on how Markdown treats this. I note, for example, the Stack Overflow answer formatter is happy with this!)

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

  1. First Possibility: The encrypted string in the Related Web.config File should be same as entered in the connection string (which is shown above) And also, when you change anything in the "Registry Editor" or regedit.exe (as written at Run), then after any change, close the registry editor and reset your Internet Information Services by typing IISRESET at Run. And then login to your environment.

  2. Type Services.msc on run and check:

    1. Status of ASP.NET State Services is started. If not, then right click on it, through Properties, change its Startup type to automatic.

    2. Iris ReportManager Service of that particular bank is Listed as Started or not. If its Running, It will show "IRIS REPORT MANAGER SERVICE" as started in the list. If not, then run it by clicking IRIS.REPORTMANAGER.EXE

    Then Again RESET IIS

How to remove \n from a list element?

Using list comprehension:

myList = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']

[(el.strip()) for el in myList]

How to crop an image using C#?

Cropping an image is very easy in C#. However, doing the stuff how are you going to manage the cropping of your image will be a little harder.

Sample below is the way how to crop an image in C#.

var filename = @"c:\personal\images\horizon.png";
var img = Image.FromFile(filename);
var rect = new Rectangle(new Point(0, 0), img.Size);
var cloned = new Bitmap(img).Clone(rect, img.PixelFormat);
var bitmap = new Bitmap(cloned, new Size(50, 50));
cloned.Dispose();

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

Bootstrap 3 collapsed menu doesn't close on click

All you need is data-target=".navbar-collapse" in the button, nothing else.

<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
</button>

How do I run a docker instance from a DockerFile?

Download the file and from the same directory run docker build -t nodebb .

This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb (you can change nodebb to your own name).

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.

ProcessStartInfo hanging on "WaitForExit"? Why?

The documentation for Process.StandardOutput says to read before you wait otherwise you can deadlock, snippet copied below:

 // Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

How to attach a file using mail command on Linux?

There are a lot of answers here using mutt or mailx or people saying mail doesn't support "-a"

First, Ubuntu 14.0.4 mail from mailutils supports this:

mail -A filename -s "subject" [email protected]

Second, I found that by using the "man mail" command and searching for "attach"

Vue.js toggle class on click

for nuxt link and bootstrap v5 navbar-nav, I used a child component

             <nuxt-link
              @click.prevent.native="isDropdwonMenuVisible = !isDropdwonMenuVisible"
              to=""
              :title="item.title"
              :class="[item.cssClasses, {show: isDropdwonMenuVisible}]"
              :id="`navbarDropdownMenuLink-${index}`"
              :aria-expanded="[isDropdwonMenuVisible ? true : false]"
              class="nav-link dropdown-toggle"
              aria-current="page"
              role="button"
              data-toggle="dropdown"
            >
              {{ item.label }}
            </nuxt-link>

data() {
    return {
      isDropdwonMenuVisible: false
    }
  },

What's the best way to iterate an Android Cursor?

The Do/While solution is more elegant, but if you do use just the While solution posted above, without the moveToPosition(-1) you will miss the first element (at least on the Contact query).

I suggest:

if (cursor.getCount() > 0) {
    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
          <do stuff>
    }
}

How do you underline a text in Android XML?

First of all, go to String.xml file

you can add any HTML attributes like , italic or bold or underline here.

    <resources>
        <string name="your_string_here">This is an <u>underline</u>.</string>
    </resources>

How can I get device ID for Admob

The accepted answers will work if you are only testing on the Emulator or on a few devices, but if you are testing on a plethora of devices, you may need some means of prorammatically adding the running device's device ID.

The following code will make the current running device into an adview test device programmatically

...
    if(YourApplication.debugEnabled(this)) //debug flag from somewhere that you set
    {

        String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = md5(android_id).toUpperCase();
        mAdRequest.addTestDevice(deviceId);
        boolean isTestDevice = mAdRequest.isTestDevice(this);

        Log.v(TAG, "is Admob Test Device ? "+deviceId+" "+isTestDevice); //to confirm it worked
    }

You need to use the md5 of the Android ID, and it needs to be upper case. Here is the md5 code I used

public static final String md5(final String s) {
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest
                .getInstance("MD5");
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < messageDigest.length; i++) {
            String h = Integer.toHexString(0xFF & messageDigest[i]);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        Logger.logStackTrace(TAG,e);
    }
    return "";
}

EDIT: Apparently that MD5 method isnt perfect, and it was suggested to try https://stackoverflow.com/a/21333739/2662474 I no longer need this feature so I havent tested. Good luck!

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

What is an NP-complete in computer science?

NP stands for Non-deterministic Polynomial time.

This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete.

The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time.

Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is.

CodeIgniter -> Get current URL relative to base url

If url helper is loaded, use

current_url();

will be better

How can I specify my .keystore file with Spring Boot and Tomcat?

It turns out that there is a way to do this, although I'm not sure I've found the 'proper' way since this required hours of reading source code from multiple projects. In other words, this might be a lot of dumb work (but it works).

First, there is no way to get at the server.xml in the embedded Tomcat, either to augment it or replace it. This must be done programmatically.

Second, the 'require_https' setting doesn't help since you can't set cert info that way. It does set up forwarding from http to https, but it doesn't give you a way to make https work so the forwarding isnt helpful. However, use it with the stuff below, which does make https work.

To begin, you need to provide an EmbeddedServletContainerFactory as explained in the Embedded Servlet Container Support docs. The docs are for Java but the Groovy would look pretty much the same. Note that I haven't been able to get it to recognize the @Value annotation used in their example but its not needed. For groovy, simply put this in a new .groovy file and include that file on the command line when you launch spring boot.

Now, the instructions say that you can customize the TomcatEmbeddedServletContainerFactory class that you created in that code so that you can alter web.xml behavior, and this is true, but for our purposes its important to know that you can also use it to tailor server.xml behavior. Indeed, reading the source for the class and comparing it with the Embedded Tomcat docs, you see that this is the only place to do that. The interesting function is TomcatEmbeddedServletContainerFactory.addConnectorCustomizers(), which may not look like much from the Javadocs but actually gives you the Embedded Tomcat object to customize yourself. Simply pass your own implementation of TomcatConnectorCustomizer and set the things you want on the given Connector in the void customize(Connector con) function. Now, there are about a billion things you can do with the Connector and I couldn't find useful docs for it but the createConnector() function in this this guys personal Spring-embedded-Tomcat project is a very practical guide. My implementation ended up looking like this:

package com.deepdownstudios.server

import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.*
import org.springframework.stereotype.*

@Configuration
class MyConfiguration {

@Bean
public EmbeddedServletContainerFactory servletContainer() {
final int port = 8443;
final String keystoreFile = "/path/to/keystore"
final String keystorePass = "keystore-password"
final String keystoreType = "pkcs12"
final String keystoreProvider = "SunJSSE"
final String keystoreAlias = "tomcat"

TomcatEmbeddedServletContainerFactory factory = 
        new TomcatEmbeddedServletContainerFactory(this.port);
factory.addConnectorCustomizers( new TomcatConnectorCustomizer() {
    void    customize(Connector con) {
        Http11NioProtocol proto = (Http11NioProtocol) con.getProtocolHandler();
            proto.setSSLEnabled(true);
        con.setScheme("https");
        con.setSecure(true);
        proto.setKeystoreFile(keystoreFile);
        proto.setKeystorePass(keystorePass);
        proto.setKeystoreType(keystoreType);
        proto.setProperty("keystoreProvider", keystoreProvider);
        proto.setKeyAlias(keystoreAlias);
    }
});
return factory;
}
}

The Autowiring will pick up this implementation an run with it. Once I fixed my busted keystore file (make sure you call keytool with -storetype pkcs12, not -storepass pkcs12 as reported elsewhere), this worked. Also, it would be far better to provide the parameters (port, password, etc) as configuration settings for testing and such... I'm sure its possible if you can get the @Value annotation to work with Groovy.

Catch multiple exceptions in one line (except block)

One of the way to do this is..

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   If there is no exception then execute this block. 

and another way is to create method which performs task executed by except block and call it through all of the except block that you write..

try:
   You do your operations here;
   ......................
except Exception1:
    functionname(parameterList)
except Exception2:
    functionname(parameterList)
except Exception3:
    functionname(parameterList)
else:
   If there is no exception then execute this block. 

def functionname( parameters ):
   //your task..
   return [expression]

I know that second one is not the best way to do this, but i'm just showing number of ways to do this thing.

How do I exit a while loop in Java?

Take a look at the Java™ Tutorials by Oracle.

But basically, as dacwe said, use break.

If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

I also wondered that long time ago. I searched a bit in my history and I think that this post: http://lists.mysql.com/internals/34919 represents the semi-official position of MySQL (before Oracle's intervention ;))

In short:

this limitation stems only from the way in which this feature is currently implemented in the server and there are no other reasons for its existence.

So their explanation is "because it is implemented like this". Doesn't sound very scientific. I guess it all comes from some old code. This is suggested in the thread above: "carry-over from when only the first timestamp field was auto-set/update".

Cheers!

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

Difference between java.exe and javaw.exe

The difference is in the subsystem that each executable targets.

  • java.exe targets the CONSOLE subsystem.
  • javaw.exe targets the WINDOWS subsystem.

Return outside function error in Python

You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

If all the other answers do not work for you check the config.inc.php for the following:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

…and add the port of MySQL set in your XAMPP as shown below:

$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';

Stop MySQL from XAMPP and restart MySQL.

Open a fresh page for http://localhost:8012/phpmyadmin/ and check.

How to get process ID of background process?

You need to save the PID of the background process at the time you start it:

foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID

You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.

Unix's 'ls' sort by name

From the man page (for bash ls):

Sort entries alphabetically if none of -cftuSUX nor --sort.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

    def wordCount(mystring):  
        tempcount = 0  
        count = 1  

        try:  
            for character in mystring:  
                if character == " ":  
                    tempcount +=1  
                    if tempcount ==1:  
                        count +=1  

                    else:  
                        tempcount +=1
                 else:
                     tempcount=0

             return count  

         except Exception:  
             error = "Not a string"  
             return error  

    mystring = "I   am having   a    very nice 23!@$      day."           

    print(wordCount(mystring))  

output is 8

Adding values to specific DataTable cells

If anyone is looking for an updated correct syntax for this as I was, try the following:

Example:
dg.Rows[0].Cells[6].Value = "test";

Why are only final variables accessible in anonymous class?

As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.

Consider the use case where your lambdas instead of being apply, is stored in some place and run later.

I remember that in Smalltalk you would get an illegal store raised when you do such modification.

ASP.NET Web Api: The requested resource does not support http method 'GET'

This is certainly a change from Beta to RC. In the example provided in the question, you now need to decorate your action with [HttpGet] or [AcceptVerbs("GET")].

This causes a problem if you want to mix verb based actions (i.e. "GetSomething", "PostSomething") with non verb based actions. If you try to use the attributes above, it will cause a conflict with any verb based action in your controller. One way to get arount that would be to define separate routes for each verb, and set the default action to the name of the verb. This approach can be used for defining child resources in your API. For example, the following code supports: "/resource/id/children" where id and children are optional.

        context.Routes.MapHttpRoute(
           name: "Api_Get",
           routeTemplate: "{controller}/{id}/{action}",
           defaults: new { id = RouteParameter.Optional, action = "Get" },
           constraints: new { httpMethod = new HttpMethodConstraint("GET") }
        );

        context.Routes.MapHttpRoute(
           name: "Api_Post",
           routeTemplate: "{controller}/{id}/{action}",
           defaults: new { id = RouteParameter.Optional, action = "Post" },
           constraints: new { httpMethod = new HttpMethodConstraint("POST") }
        );

Hopefully future versions of Web API will have better support for this scenario. There is currently an issue logged on the aspnetwebstack codeplex project, http://aspnetwebstack.codeplex.com/workitem/184. If this is something you would like to see, please vote on the issue.

How to concatenate text from multiple rows into a single text string in SQL server?

DECLARE @Names VARCHAR(8000)
SELECT @name = ''
SELECT @Names = @Names + ',' + Names FROM People
SELECT SUBSTRING(2, @Names, 7998)

This puts the stray comma at the beginning.

However, if you need other columns, or to CSV a child table you need to wrap this in a scalar user defined field (UDF).

You can use XML path as a correlated subquery in the SELECT clause too (but I'd have to wait until I go back to work because Google doesn't do work stuff at home :-)

simple custom event

You haven't created an event. To do that write:

public event EventHandler<Progress> Progress;

Then, you can call Progress from within the class where it was declared like normal function or delegate:

Progress(this, new Progress("some status"));

So, if you want to report progress in TestClass, the event should be in there too and it should be also static. You can the subscribe to it from your form like this:

TestClass.Progress += SetStatus;

Also, you should probably rename Progress to ProgressEventArgs, so that it's clear what it is.

How to reset the state of a Redux store?

One way to do that would be to write a root reducer in your application.

The root reducer would normally delegate handling the action to the reducer generated by combineReducers(). However, whenever it receives USER_LOGOUT action, it returns the initial state all over again.

For example, if your root reducer looked like this:

const rootReducer = combineReducers({
  /* your app’s top-level reducers */
})

You can rename it to appReducer and write a new rootReducer delegating to it:

const appReducer = combineReducers({
  /* your app’s top-level reducers */
})

const rootReducer = (state, action) => {
  return appReducer(state, action)
}

Now we just need to teach the new rootReducer to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action. Let’s use this fact to conditionally strip the accumulated state as we pass it to appReducer:

 const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    state = undefined
  }

  return appReducer(state, action)
}

Now, whenever USER_LOGOUT fires, all reducers will be initialized anew. They can also return something different than they did initially if they want to because they can check action.type as well.

To reiterate, the full new code looks like this:

const appReducer = combineReducers({
  /* your app’s top-level reducers */
})

const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    state = undefined
  }

  return appReducer(state, action)
}

Note that I’m not mutating the state here, I am merely reassigning the reference of a local variable called state before passing it to another function. Mutating a state object would be a violation of Redux principles.

In case you are using redux-persist, you may also need to clean your storage. Redux-persist keeps a copy of your state in a storage engine, and the state copy will be loaded from there on refresh.

First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.

const rootReducer = (state, action) => {
    if (action.type === SIGNOUT_REQUEST) {
        // for all keys defined in your persistConfig(s)
        storage.removeItem('persist:root')
        // storage.removeItem('persist:otherKey')

        state = undefined;
    }
    return appReducer(state, action);
};

Jquery get input array field

Use the starts with selector

$('input[name^="pages_title"]').each(function() {
    alert($(this).val());
});

jsfiddle example

Note: In agreement with @epascarello that the better solution is to add a class to the elements and reference that class.

How to Retrieve value from JTextField in Java Swing?

You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass

Why can't I make a vector of references?

As other have mentioned, you will probably end up using a vector of pointers instead.

However, you may want to consider using a ptr_vector instead!

How to use Google App Engine with my own naked domain (not subdomain)?

When you go to "Application Settings -> Add Domain" It will ask to select login account, probably you are already on gmail account so it will show gmail account as well, but you should use Google Apps account where you have mapped your custom domain.

Getting View's coordinates relative to the root layout

No need to calculate it manually.

Just use getGlobalVisibleRect like so:

Rect myViewRect = new Rect();
myView.getGlobalVisibleRect(myViewRect);
float x = myViewRect.left;
float y = myViewRect.top;

Also note that for the centre coordinates, rather than something like:

...
float two = (float) 2
float cx = myViewRect.left + myView.getWidth() / two;
float cy = myViewRect.top + myView.getHeight() / two;

You can just do:

float cx = myViewRect.exactCenterX();
float cy = myViewRect.exactCenterY();

ScriptManager.RegisterStartupScript code not working - why?

I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.

Using WGET to run a cronjob PHP

you can just use this code to hit the script using cron job using cpanel:

wget https://www.example.co.uk/unique-code