Programs & Examples On #Clutter gui

How to change value of ArrayList element in java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

What's the difference between a mock & stub?

I came across this interesting article by UncleBob The Little Mocker. It explains all the terminology in a very easy to understand manner, so its useful for beginners. Martin Fowlers article is a hard read especially for beginners like me.

How to destroy a JavaScript object?

You can't delete objects, they are removed when there are no more references to them. You can delete references with delete.

However, if you have created circular references in your objects you may have to de-couple some things.

How to return a result (startActivityForResult) from a TabHost Activity?

http://tylenoly.wordpress.com/2010/10/27/how-to-finish-activity-with-results/

With a slight modification for "param_result"

/* Start Activity */
public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setClassName("com.thinoo.ActivityTest", "com.thinoo.ActivityTest.NewActivity");
    startActivityForResult(intent,90);
}
/* Called when the second activity's finished */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 90:
        if (resultCode == RESULT_OK) {
            Bundle res = data.getExtras();
            String result = res.getString("param_result");
            Log.d("FIRST", "result:"+result);
        }
        break;
    }
}

private void finishWithResult()
{
    Bundle conData = new Bundle();
    conData.putString("param_result", "Thanks Thanks");
    Intent intent = new Intent();
    intent.putExtras(conData);
    setResult(RESULT_OK, intent);
    finish();
}

starting file download with JavaScript

Just call window.location.href = new_url from your javascript and it will redirect the browser to that URL as it the user had typed that into the address bar

Cross-Origin Request Headers(CORS) with PHP headers

I've simply managed to get dropzone and other plugin to work with this fix (angularjs + php backend)

 header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

add this in your upload.php or where you would send your request (for example if you have upload.html and you need to attach the files to upload.php, then copy and paste these 4 lines). Also if you're using CORS plugins/addons in chrome/mozilla be sure to toggle them more than one time,in order for CORS to be enabled

Show/hide 'div' using JavaScript

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

HashMap allows duplicates?

m.put(null,null); // here key=null, value=null
m.put(null,a);    // here also key=null, and value=a

Duplicate keys are not allowed in hashmap.
However,value can be duplicated.

C - Convert an uppercase letter to lowercase

In ASCII the upper and lower case alphabet are 0x20 apart from each other, so this is another way to do it.

int lower(int a) 
{
    if ((a >= 0x41) && (a <= 0x5A))
        a |= 0x20; 
    return a;  
}

Pandas read_csv from url

As I commented you need to use a StringIO object and decode i.e c=pd.read_csv(io.StringIO(s.decode("utf-8"))) if using requests, you need to decode as .content returns bytes if you used .text you would just need to pass s as is s = requests.get(url).text c = pd.read_csv(StringIO(s)).

A simpler approach is to pass the correct url of the raw data directly to read_csv, you don't have to pass a file like object, you can pass a url so you don't need requests at all:

c = pd.read_csv("https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv")

print(c)

Output:

                              Country         Region
0                             Algeria         AFRICA
1                              Angola         AFRICA
2                               Benin         AFRICA
3                            Botswana         AFRICA
4                             Burkina         AFRICA
5                             Burundi         AFRICA
6                            Cameroon         AFRICA
..................................

From the docs:

filepath_or_buffer :

string or file handle / StringIO The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.csv

How to make layout with rounded corners..?

I think a better way to do it is to merge 2 things:

  1. make a bitmap of the layout, as shown here.

  2. make a rounded drawable from the bitmap, as shown here

  3. set the drawable on an imageView.

This will handle cases that other solutions have failed to solve, such as having content that has corners.

I think it's also a bit more GPU-friendly, as it shows a single layer instead of 2 .

The only better way is to make a totally customized view, but that's a lot of code and might take a lot of time. I think that what I suggested here is the best of both worlds.

Here's a snippet of how it can be done:

RoundedCornersDrawable.java

/**
 * shows a bitmap as if it had rounded corners. based on :
 * http://rahulswackyworld.blogspot.co.il/2013/04/android-drawables-with-rounded_7.html
 * easy alternative from support library: RoundedBitmapDrawableFactory.create( ...) ; 
 */
public class RoundedCornersDrawable extends BitmapDrawable {

    private final BitmapShader bitmapShader;
    private final Paint p;
    private final RectF rect;
    private final float borderRadius;

    public RoundedCornersDrawable(final Resources resources, final Bitmap bitmap, final float borderRadius) {
        super(resources, bitmap);
        bitmapShader = new BitmapShader(getBitmap(), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        final Bitmap b = getBitmap();
        p = getPaint();
        p.setAntiAlias(true);
        p.setShader(bitmapShader);
        final int w = b.getWidth(), h = b.getHeight();
        rect = new RectF(0, 0, w, h);
        this.borderRadius = borderRadius < 0 ? 0.15f * Math.min(w, h) : borderRadius;
    }

    @Override
    public void draw(final Canvas canvas) {
        canvas.drawRoundRect(rect, borderRadius, borderRadius, p);
    }
}

CustomView.java

public class CustomView extends ImageView {
    private View mMainContainer;
    private boolean mIsDirty=false;

    // TODO for each change of views/content, set mIsDirty to true and call invalidate

    @Override
    protected void onDraw(final Canvas canvas) {
        if (mIsDirty) {
            mIsDirty = false;
            drawContent();
            return;
        }
        super.onDraw(canvas);
    }

    /**
     * draws the view's content to a bitmap. code based on :
     * http://nadavfima.com/android-snippet-inflate-a-layout-draw-to-a-bitmap/
     */
    public static Bitmap drawToBitmap(final View viewToDrawFrom, final int width, final int height) {
        // Create a new bitmap and a new canvas using that bitmap
        final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bmp);
        viewToDrawFrom.setDrawingCacheEnabled(true);
        // Supply measurements
        viewToDrawFrom.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
        // Apply the measures so the layout would resize before drawing.
        viewToDrawFrom.layout(0, 0, viewToDrawFrom.getMeasuredWidth(), viewToDrawFrom.getMeasuredHeight());
        // and now the bmp object will actually contain the requested layout
        canvas.drawBitmap(viewToDrawFrom.getDrawingCache(), 0, 0, new Paint());
        return bmp;
    }

    private void drawContent() {
        if (getMeasuredWidth() <= 0 || getMeasuredHeight() <= 0)
            return;
        final Bitmap bitmap = drawToBitmap(mMainContainer, getMeasuredWidth(), getMeasuredHeight());
        final RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), bitmap, 15);
        setImageDrawable(drawable);
    }

}

EDIT: found a nice alternative, based on "RoundKornersLayouts" library. Have a class that will be used for all of the layout classes you wish to extend, to be rounded:

//based on https://github.com/JcMinarro/RoundKornerLayouts
class CanvasRounder(cornerRadius: Float, cornerStrokeColor: Int = 0, cornerStrokeWidth: Float = 0F) {
    private val path = android.graphics.Path()
    private lateinit var rectF: RectF
    private var strokePaint: Paint?
    var cornerRadius: Float = cornerRadius
        set(value) {
            field = value
            resetPath()
        }

    init {
        if (cornerStrokeWidth <= 0)
            strokePaint = null
        else {
            strokePaint = Paint()
            strokePaint!!.style = Paint.Style.STROKE
            strokePaint!!.isAntiAlias = true
            strokePaint!!.color = cornerStrokeColor
            strokePaint!!.strokeWidth = cornerStrokeWidth
        }
    }

    fun round(canvas: Canvas, drawFunction: (Canvas) -> Unit) {
        val save = canvas.save()
        canvas.clipPath(path)
        drawFunction(canvas)
        if (strokePaint != null)
            canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, strokePaint)
        canvas.restoreToCount(save)
    }

    fun updateSize(currentWidth: Int, currentHeight: Int) {
        rectF = android.graphics.RectF(0f, 0f, currentWidth.toFloat(), currentHeight.toFloat())
        resetPath()
    }

    private fun resetPath() {
        path.reset()
        path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW)
        path.close()
    }

}

Then, in each of your customized layout classes, add code similar to this one:

class RoundedConstraintLayout : ConstraintLayout {
    private lateinit var canvasRounder: CanvasRounder

    constructor(context: Context) : super(context) {
        init(context, null, 0)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        init(context, attrs, defStyle)
    }

    private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
        val array = context.obtainStyledAttributes(attrs, R.styleable.RoundedCornersView, 0, 0)
        val cornerRadius = array.getDimension(R.styleable.RoundedCornersView_corner_radius, 0f)
        val cornerStrokeColor = array.getColor(R.styleable.RoundedCornersView_corner_stroke_color, 0)
        val cornerStrokeWidth = array.getDimension(R.styleable.RoundedCornersView_corner_stroke_width, 0f)
        array.recycle()
        canvasRounder = CanvasRounder(cornerRadius,cornerStrokeColor,cornerStrokeWidth)
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            setLayerType(FrameLayout.LAYER_TYPE_SOFTWARE, null)
        }
    }

    override fun onSizeChanged(currentWidth: Int, currentHeight: Int, oldWidth: Int, oldheight: Int) {
        super.onSizeChanged(currentWidth, currentHeight, oldWidth, oldheight)
        canvasRounder.updateSize(currentWidth, currentHeight)
    }

    override fun draw(canvas: Canvas) = canvasRounder.round(canvas) { super.draw(canvas) }

    override fun dispatchDraw(canvas: Canvas) = canvasRounder.round(canvas) { super.dispatchDraw(canvas) }

}

If you wish to support attributes, use this as written on the library:

<resources>
  <declare-styleable name="RoundedCornersView">
      <attr name="corner_radius" format="dimension"/>
      <attr name="corner_stroke_width" format="dimension"/>
      <attr name="corner_stroke_color" format="color"/>
  </declare-styleable>
</resources>

Another alternative, which might be easier for most uses: use MaterialCardView . It allows customizing the rounded corners, stroke color and width, and elevation.

Example:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false"
    tools:context=".MainActivity">

    <com.google.android.material.card.MaterialCardView
        android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center"
        app:cardCornerRadius="8dp" app:cardElevation="8dp" app:strokeColor="#f00" app:strokeWidth="2dp">

        <ImageView
            android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0f0"/>

    </com.google.android.material.card.MaterialCardView>

</FrameLayout>

And the result:

enter image description here

Do note that there is a slight artifacts issue at the edges of the stroke (leaves some pixels of the content there), if you use it. You can notice it if you zoom in. I've reported about this issue here.

EDIT: seems to be fixed, but not on the IDE. Reported here.

How to print out all the elements of a List in Java?

I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters. Javadoc:

Dumps an given Object to System.out, using the following rules:

  • If the Object is Iterable, all of its components are dumped.
  • If the Object or one of its superclasses overrides toString(), the "toString" is dumped
  • Else the method is called recursively for all public members of the Object

/**
 * Dumps an given Object to System.out, using the following rules:<br>
 * <ul>
 * <li> If the Object is {@link Iterable}, all of its components are dumped.</li>
 * <li> If the Object or one of its superclasses overrides {@link #toString()}, the "toString" is dumped</li>
 * <li> Else the method is called recursively for all public members of the Object </li>
 * </ul>
 * @param input
 * @throws Exception
 */
public static void dump(Object input) throws Exception{
    dump(input, 0);
}

private static void dump(Object input, int depth) throws Exception{
    if(input==null){
        System.out.print("null\n"+indent(depth));
        return;
    }

    Class<? extends Object> clazz = input.getClass();
    System.out.print(clazz.getSimpleName()+" ");
    if(input instanceof Iterable<?>){
        for(Object o: ((Iterable<?>)input)){
            System.out.print("\n"+indent(depth+1));
            dump(o, depth+1);
        }
    }else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
        Field[] fields = clazz.getFields();
        if(fields.length == 0){
            System.out.print(input+"\n"+indent(depth));
        }
        System.out.print("\n"+indent(depth+1));
        for(Field field: fields){
            Object o = field.get(input);
            String s = "|- "+field.getName()+": ";
            System.out.print(s);
            dump(o, depth+1);
        }
    }else{

        System.out.print(input+"\n"+indent(depth));
    }
}

private static String indent(int depth) {
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<depth; i++)
        sb.append("  ");
    return sb.toString();
}

How to restore default perspective settings in Eclipse IDE

There is no keyboard shortcut for restoring the perspective directly AFAIK. To open the Window menu (where Reset Perspective resides), try Alt-W. If that does not work, I guess your Eclipse has hung for some reason. Another shortcut you might want to try is F10 (should open the main menu).

How can I generate an ObjectId with mongoose?

With ES6 syntax

import mongoose from "mongoose";

// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

How to debug a Flask app

Use loggers and print statements in the Development Environment, you can go for sentry in case of production environments.

How to force JS to do math instead of putting two strings together

You have the line

dots = document.getElementById("txt").value;

in your file, this will set dots to be a string because the contents of txt is not restricted to a number.

to convert it to an int change the line to:

dots = parseInt(document.getElementById("txt").value, 10);

Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.

C# get string from textbox

The TextBox control has a Text property that you can use to get (or set) the text of the textbox.

How do I find the difference between two values without knowing which is larger?

abs(x-y) will do exactly what you're looking for:

In [1]: abs(1-2)
Out[1]: 1

In [2]: abs(2-1)
Out[2]: 1

Entity framework self referencing loop detected

Self-referencing as example

public class Employee {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public int ManagerId { get; set; }
    public virtual Employee Manager { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }

    public Employee() {
        Employees = new HashSet<Employee>();
    }
}
HasMany(e => e.Employees)
    .WithRequired(e => e.Manager)
    .HasForeignKey(e => e.ManagerId)
    .WillCascadeOnDelete(false);

Display last git commit comment

I did this

git reflog -1 | sed 's/^.*: //'

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

Repeat command automatically in Linux

If the command contains some special characters such as pipes and quotes, the command needs to be padded with quotes. For example, to repeat ls -l | grep "txt", the watch command should be:

watch -n 5 'ls -l | grep "txt"'

Fixed height and width for bootstrap carousel

To have a consistent flow of the images on different devices, you'd have to specify the width and height value for each carousel image item, for instance here in my example the image would take the full width but with a height of "400px" (you can specify your personal value instead)

<div class="item">
        <img src="image.jpg" style="width:100%; height: 400px;">
      </div>

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

Switch statement fall-through...should it be allowed?

It is powerful and dangerous. The biggest problem with fall-through is that it's not explicit. For example, if you come across frequently-edited code that has a switch with fall-throughs, how do you know that's intentional and not a bug?

Anywhere I use it, I ensure that it's properly commented:

switch($var) {
    case 'first':
        // Fall-through
    case 'second':
        i++;
        break;
 }

Remove last character of a StringBuilder?

Alternatively,

StringBuilder result = new StringBuilder();
for(String string : collection) {
    result.append(string);
    result.append(',');
}
return result.substring(0, result.length() - 1) ;

Return Type for jdbcTemplate.queryForList(sql, object, classType)

In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.

See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.

In short, you'll need something like:

List<Conversation> actors = jdbcTemplate.query(
    SELECT_ALL_CONVERSATIONS_SQL_FULL,
    new Object[] {userId, dateFrom, dateTo},
    new RowMapper<Conversation>() {
        public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
            Conversation c = new Conversation();
            c.setId(rs.getLong(1));
            c.setRoom(rs.getString(2));
            [...]
            return c;
        }
    });

Which sort algorithm works best on mostly sorted data?

Bubble sort is definitely the winner The next one on the radar would be insertion sort.

How to sort a data frame by date

Nowadays, it is the most efficient and comfortable to use lubridate and dplyr libraries.

lubridate contains a number of functions that make parsing dates into POSIXct or Date objects easy. Here we use dmy which automatically parses dates in Day, Month, Year formats. Once your data is in a date format, you can sort it with dplyr::arrange (or any other ordering function) as desired:

d$V3 <- lubridate::dmy(d$V3)
dplyr::arrange(d, V3)

What's the best way to share data between activities?

Using the hashmap of weak reference approach, described above, and in http://developer.android.com/guide/faq/framework.html seems problematic to me. How are entire entries reclaimed, not just the map value? What scope do you allocate it in? As the framework is in control of the Activity lifecycle, having one of the participating Activities own it risks runtime errors when the owner is destroyed in advance of its clients. If the Application owns it, some Activity must explicitly remove the entry to avoid the hashmap from holding on to entries with a valid key and a potentially garbaged collected weak reference. Furthermore, what should a client do when the value returned for a key is null?

It seems to me that a WeakHashMap owned by the Application or within a singleton is a better choice. An value in the map is accessed via a key object, and when no strong references to the key exist (i.e. all Activities are done with the key and what it maps to), GC can reclaim the map entry.

AngularJS : How do I switch views from a controller function?

There are two ways for this:

If you are using ui-router or $stateProvider, do it as:

$state.go('stateName'); //remember to add $state service in the controller

if you are using angular-router or $routeProvider, do it as:

$location.path('routeName'); //similarily include $location service in your controller

What does $1 mean in Perl?

Since you asked about the capture groups, you might want to know about $+ too... Pretty useful...

use Data::Dumper;
$text = "hiabc ihabc ads byexx eybxx";
while ($text =~ /(hi|ih)abc|(bye|eyb)xx/igs)
{
    print Dumper $+;
}

OUTPUT:
$VAR1 = 'hi';
$VAR1 = 'ih';
$VAR1 = 'bye';
$VAR1 = 'eyb';

Unable to Cast from Parent Class to Child Class

The instance of the object should be created using the child class's type, you can't cast a parent type instance to a child type

Find a commit on GitHub given the commit hash

A URL of the form https://github.com/<owner>/<project>/commit/<hash> will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:

https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685

You can also shorten the hash to any unique prefix, like so:

https://github.com/jerith666/git-graph/commit/35e32b


I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):

git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685

Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.

rmagick gem install "Can't find Magick-config"

Ubuntu 15.10

Note that if you try to install this gem in ubuntu 15.10, then error can happened:

Can't install RMagick 2.13.1. Can't find Magick-config in ...

All you need is preload PATH variable with additional path to ImageMagick lib.

PATH="/usr/lib/x86_64-linux-gnu/ImageMagick-6.8.9/bin-Q16:$PATH"

then run gem install rmagick

source of solution

How to center the elements in ConstraintLayout

You can center a view as a percentage of the screen size.

This example uses 50% of width and height:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FF0000"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_percent=".5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent=".5"></LinearLayout>

</android.support.constraint.ConstraintLayout>

This was done using ConstraintLayout version 1.1.3. Don't forget to add it to your dependencies in the gradle, and increase the version if there is a new version out there:

dependencies {
...
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

enter image description here

How to get index in Handlebars each helper?

In handlebar version 3.0 onwards,

{{#each users as |user userId|}}
  Id: {{userId}} Name: {{user.name}}
{{/each}}

In this particular example, user will have the same value as the current context and userId will have the index value for the iteration. Refer - http://handlebarsjs.com/block_helpers.html in block helpers section

How to parse a JSON object to a TypeScript Object

You can cast the the json as follows:

Given your class:

export class Employee{
    firstname: string= '';
}

and the json:

let jsonObj = {
    "firstname": "Hesham"
};

You can cast it as follows:

let e: Employee = jsonObj as Employee;

And the output of console.log(e); is:

{ firstname: 'Hesham' }

Why does Math.Round(2.5) return 2 instead of 3?

Since Silverlight doesn't support the MidpointRounding option you have to write your own. Something like:

public double RoundCorrect(double d, int decimals)
{
    double multiplier = Math.Pow(10, decimals);

    if (d < 0)
        multiplier *= -1;

    return Math.Floor((d * multiplier) + 0.5) / multiplier;

}

For the examples including how to use this as an extension see the post: .NET and Silverlight Rounding

convert date string to mysql datetime field

If these strings are currently in the db, you can skip php by using mysql's STR_TO_DATE() function.

I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.

UPDATE some_table
   SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y')

You can support other date formats by using other format specifiers.

How to allow download of .json file with ASP.NET

Solution is you need to add json file extension type in MIME Types

Method 1

Go to IIS, Select your application and Find MIME Types

enter image description here

Click on Add from Right panel

File Name Extension = .json

MIME Type = application/json

enter image description here

After adding .json file type in MIME Types, Restart IIS and try to access json file


Method 2

Go to web.config of that application and add this lines in it

 <system.webServer>
   <staticContent>
     <mimeMap fileExtension=".json" mimeType="application/json" />
   </staticContent>
 </system.webServer>

How can I find the link URL by link text with XPath?

Think of the phrase in the square brackets as a WHERE clause in SQL.

So this query says, "select the "href" attribute (@) of an "a" tag that appears anywhere (//), but only where (the bracketed phrase) the textual contents of the "a" tag is equal to 'programming questions site'".

How to change position of Toast in Android?

Toast mytoast= Toast.makeText(getApplicationContext(), "Toast Message", 1);  
mytoast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);  // for center horizontal
//mytoast.setGravity(Gravity.CENTER_VERTICAL);       // for center vertical 
//mytoast.setGravity(Gravity.TOP);                       // for top
mytoast.show();

The above code is will help u to display toast in the middle of screen or according to ur choice for that just set the toast gravity according to ur need

Note: For this process u have to use object of Toast

Making a list of evenly spaced numbers in a certain range in python

Similar to Howard's answer but a bit more efficient:

def my_func(low, up, leng):
    step = ((up-low) * 1.0 / leng)
    return [low+i*step for i in xrange(leng)]

What is the simplest way to convert array to vector?

You're asking the wrong question here - instead of forcing everything into a vector ask how you can convert test to work with iterators instead of a specific container. You can provide an overload too in order to retain compatibility (and handle other containers at the same time for free):

void test(const std::vector<int>& in) {
  // Iterate over vector and do whatever
}

becomes:

template <typename Iterator>
void test(Iterator begin, const Iterator end) {
    // Iterate over range and do whatever
}

template <typename Container>
void test(const Container& in) {
    test(std::begin(in), std::end(in));
}

Which lets you do:

int x[3]={1, 2, 3};
test(x); // Now correct

(Ideone demo)

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

Get a list of dates between two dates

Typically one would use an auxiliary numbers table you usually keep around for just this purpose with some variation on this:

SELECT *
FROM (
    SELECT DATEADD(d, number - 1, '2009-01-01') AS dt
    FROM Numbers
    WHERE number BETWEEN 1 AND DATEDIFF(d, '2009-01-01', '2009-01-13') + 1
) AS DateRange
LEFT JOIN YourStuff
    ON DateRange.dt = YourStuff.DateColumn

I've seen variations with table-valued functions, etc.

You can also keep a permanent list of dates. We have that in our data warehouse as well as a list of times of day.

Launch a shell command with in a python script, wait for the termination and return to the script

The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

Check if one list contains element from the other

Loius answer is correct, I just want to add an example:

listOne.add("A");
listOne.add("B");
listOne.add("C");

listTwo.add("D");
listTwo.add("E");
listTwo.add("F");      

boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

Source file 'Properties\AssemblyInfo.cs' could not be found

I got the error using TFS, my AssemblyInfo wasn't mapped in the branch I was working on.

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Run XAMPP Control Panel as Administrator if using Windows 7 or more. Windows may block access to ports if not accessed by adminstrator user.

What's the actual use of 'fail' in JUnit test case?

In concurrent and/or asynchronous settings, you may want to verify that certain methods (e.g. delegates, event listeners, response handlers, you name it) are not called. Mocking frameworks aside, you can call fail() in those methods to fail the tests. Expired timeouts are another natural failure condition in such scenarios.

For example:

final CountDownLatch latch = new CountDownLatch(1);

service.asyncCall(someParameter, new ResponseHandler<SomeType>() {
    @Override
    public void onSuccess(SomeType result) {
        assertNotNull(result);
        // Further test assertions on the result
        latch.countDown();
    }

    @Override
    public void onError(Exception e) {
        fail(exception.getMessage());
        latch.countDown();
    }
});

if ( !latch.await(5, TimeUnit.SECONDS) ) {
    fail("No response after 5s");
}

Using TortoiseSVN via the command line

To use command support you should follow this steps:

  1. Define Path in Environment Variables:

    • open 'System Properties';
    • on the tab 'Advanced' click on the 'Environment Variables' button
    • in the section 'System variables' select 'Path' option and click 'edit'
    • append variable value with the path to TortoiseProc.exe file, for example:

      C:\Program Files\TortoiseSVN\bin

  2. Since you have registered TortoiseProc, you can use it in according to TortoiseSVN documentation.

    Examples:

    TortoiseProc.exe /command:commit /path:"c:\svn_wc\file1.txt*c:\svn_wc\file2.txt" /logmsg:"test log message" /closeonend:0

    TortoiseProc.exe /command:update /path:"c:\svn_wc\" /closeonend:0

    TortoiseProc.exe /command:log /path:"c:\svn_wc\file1.txt" /startrev:50 /endrev:60 /closeonend:0

P.S. To use friendly name like 'svn' instead of 'TortoiseProc', place 'svn.bat' file in the directory of 'TortoiseProc.exe'. There is an example of svn.bat:

TortoiseProc.exe %1 %2 %3

Getting multiple values with scanf()

Could do this, but then the user has to separate the numbers by a space:

#include "stdio.h"

int main()
{
    int minx, x, y, z;

    printf("Enter four ints: ");
    scanf( "%i %i %i %i", &minx, &x, &y, &z);

    printf("You wrote: %i %i %i %i", minx, x, y, z);
}

if-else statement inside jsx: ReactJS

As per DOC:

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

Basic Rule:

JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expression in JSX by wrapping it in curly braces.

But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.


If you want to render the element conditionally then use ternary operator, like this:

render() {
    return (   
        <View style={styles.container}>
            {this.state.value == 'news'? <Text>data</Text>: null }
        </View>
    )
}

Another option is, call a function from jsx and put all the if-else logic inside that, like this:

renderElement(){
   if(this.state.value == 'news')
      return <Text>data</Text>;
   return null;
}

render() {
    return (   
        <View style={styles.container}>
            { this.renderElement() }
        </View>
    )
}

Monitor network activity in Android Phones

Preconditions: adb and wireshark are installed on your computer and you have a rooted android device.

  1. Download tcpdump to ~/Downloads
  2. adb push ~/Downloads/tcpdump /sdcard/
  3. adb shell
  4. su root
  5. mv /sdcard/tcpdump /data/local/
  6. cd /data/local/
  7. chmod +x tcpdump
  8. ./tcpdump -vv -i any -s 0 -w /sdcard/dump.pcap
  9. Ctrl+C once you've captured enough data.
  10. exit
  11. exit
  12. adb pull /sdcard/dump.pcap ~/Downloads/

Now you can open the pcap file using Wireshark.

As for your question about monitoring specific processes, find the bundle id of your app, let's call it com.android.myapp

  1. ps | grep com.android.myapp
  2. copy the first number you see from the output. Let's call it 1234. If you see no output, you need to start the app.
  3. Download strace to ~/Downloads and put into /data/local using the same way you did for tcpdump above.
  4. cd /data/local
  5. ./strace -p 1234 -f -e trace=network -o /sdcard/strace.txt

Now you can look at strace.txt for ip addresses, and filter your wireshark log for those IPs.

How do I use the built in password reset/change views with my own templates

The documentation says that there only one context variable, form.

If you're having trouble with login (which is common), the documentation says there are three context variables:

  • form: A Form object representing the login form. See the forms documentation for more on Form objects.
  • next: The URL to redirect to after successful login. This may contain a query string, too.
  • site_name: The name of the current Site, according to the SITE_ID setting.

How to unzip a file using the command line?

Grab an executable from info-zip.

Info-ZIP supports hardware from microcomputers all the way up to Cray supercomputers, running on almost all versions of Unix, VMS, OS/2, Windows 9x/NT/etc. (a.k.a. Win32), Windows 3.x, Windows CE, MS-DOS, AmigaDOS, Atari TOS, Acorn RISC OS, BeOS, Mac OS, SMS/QDOS, MVS and OS/390 OE, VM/CMS, FlexOS, Tandem NSK and Human68K (Japanese). There is also some (old) support for LynxOS, TOPS-20, AOS/VS and Novell NLMs. Shared libraries (DLLs) are available for Unix, OS/2, Win32 and Win16, and graphical interfaces are available for Win32, Win16, WinCE and Mac OS.

Is "&#160;" a replacement of "&nbsp;"?

  • &nbsp; is the character entity reference (meant to be easily parseable by humans).
  • &#160; is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

How to change dataframe column names in pyspark?

There are many ways to do that:

  • Option 1. Using selectExpr.

    data = sqlContext.createDataFrame([("Alberto", 2), ("Dakota", 2)], 
                                      ["Name", "askdaosdka"])
    data.show()
    data.printSchema()
    
    # Output
    #+-------+----------+
    #|   Name|askdaosdka|
    #+-------+----------+
    #|Alberto|         2|
    #| Dakota|         2|
    #+-------+----------+
    
    #root
    # |-- Name: string (nullable = true)
    # |-- askdaosdka: long (nullable = true)
    
    df = data.selectExpr("Name as name", "askdaosdka as age")
    df.show()
    df.printSchema()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
    #root
    # |-- name: string (nullable = true)
    # |-- age: long (nullable = true)
    
  • Option 2. Using withColumnRenamed, notice that this method allows you to "overwrite" the same column. For Python3, replace xrange with range.

    from functools import reduce
    
    oldColumns = data.schema.names
    newColumns = ["name", "age"]
    
    df = reduce(lambda data, idx: data.withColumnRenamed(oldColumns[idx], newColumns[idx]), xrange(len(oldColumns)), data)
    df.printSchema()
    df.show()
    
  • Option 3. using alias, in Scala you can also use as.

    from pyspark.sql.functions import col
    
    data = data.select(col("Name").alias("name"), col("askdaosdka").alias("age"))
    data.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
  • Option 4. Using sqlContext.sql, which lets you use SQL queries on DataFrames registered as tables.

    sqlContext.registerDataFrameAsTable(data, "myTable")
    df2 = sqlContext.sql("SELECT Name AS name, askdaosdka as age from myTable")
    
    df2.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

I had the very same problem in my development environment. It was resolved using http://127.0.0.1:8000 instead of http://localhost:8000.

Scanning Java annotations at runtime

There's a wonderful comment by zapp that sinks in all those answers:

new Reflections("my.package").getTypesAnnotatedWith(MyAnnotation.class)

What is the difference between require and require-dev sections in composer.json?

General rule is that you want packages from require-dev section only in development (dev) environments, for example local environment.

Packages in require-dev section are packages which help you debug app, run tests etc.

At staging and production environment you probably want only packages from require section.

But anyway you can run composer install --no-dev and composer update --no-dev on any environment, command will install only packages from required section not from require-dev, but probably you want to run this only at staging and production environments not on local.

Theoretically you can put all packages in require section and nothing will happened, but you don't want developing packages at production environment because of the following reasons :

  1. speed
  2. potential of expose some debuging info
  3. etc

Some good candidates for require-dev are :

"filp/whoops": "^2.0",
"fzaninotto/faker": "^1.4",
"mockery/mockery": "^1.0",
"nunomaduro/collision": "^2.0",
"phpunit/phpunit": "^7.0"

you can see what above packages are doing and you will see why you don't need them on production.

See more here : https://getcomposer.org/doc/04-schema.md

iterate through a map in javascript

I'd use standard javascript:

for (var m in myMap){
    for (var i=0;i<myMap[m].length;i++){
    ... do something with myMap[m][i] ...
    }
} 

Note the different ways of treating objects and arrays.

Java generating Strings with placeholders

StrSubstitutor from Apache Commons Lang may be used for string formatting with named placeholders:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.1</version>
</dependency>

https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html :

Substitutes variables within a string by values.

This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods.

Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.

Example:

String template = "Hi ${name}! Your number is ${number}";

Map<String, String> data = new HashMap<String, String>();
data.put("name", "John");
data.put("number", "1");

String formattedString = StrSubstitutor.replace(template, data);

Add a pipe separator after items in an unordered list unless that item is the last on a line

Just

li + li::before {
    content: " | ";
}

Of course, this does not actually solve the OP's problem. He wants to elide the vertical bars at the beginning and end of lines depending on where they are broken. I will go out on a limb and assert that this problem is not solvable using CSS, and not even with JS unless one wants to essentially rewrite the browser engine's text-measurement/layout/line breaking logic.

The only pieces of CSS, as far as I can see, that "know" about line breaking are, first, the ::first-line pseudo element, which does not help us here--in any case, it is limited to a few presentational attributes, and does not work together with things like ::before and ::after. The only other aspect of CSS I can think of that to some extent exposes line-breaking is hyphenation. However, hyphenating is all about adding a character (usually a dash) to the end of lines in certain situations, whereas here we are concerned about removing a character (the vertical line), so I just can't see how to apply any kind of hyphenation-related logic, even with the help of properties such as hyphenate-character.

We have the word-spacing property, which is applied intra-line but not at line beginnings and endings, which seems promising, but it defines the width of the space between words, not the character(s) to be used.

One wonders if there's some way to use the text-overflow property, which has the little-known ability to take two values for display of overflow text at both left and right, as in

text-overflow: '' '';

but there still doesn't seem to be any obvious way to get from A to B here.

How can I list (ls) the 5 last modified files in a directory?

The accepted answer lists only the filenames, but to get the top 5 files one can also use:

ls -lht | head -6

where:

-l outputs in a list format

-h makes output human readable (i.e. file sizes appear in kb, mb, etc.)

-t sorts output by placing most recently modified file first

head -6 will show 5 files because ls prints the block size in the first line of output.

I think this is a slightly more elegant and possibly more useful approach.

Example output:

total 26960312 -rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py -rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf -rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf -rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf -rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

I'm using Nexus 7 (4.2) on Windows 7 x64. None of the other methods described here worked for me. The tab was already in PTP mode. Finally, I could get it working when I added the below line to 'android_winusb.inf' under <android-sdk>\extras\google\usb_driver and did an 'update driver':

%CompositeAdbInterface%     = USB_Install, USB\VID_18D1&PID_4E44&REV_9999&MI_01

To get the exact hardware ID (USB\VID_18D1&PID_4E44&REV_9999&MI_01 in my case), you can go to Computer Management -> Device Manager -> Details tab -> select Hardware Id from the drop-down.

Difference between array_map, array_walk and array_filter

From the documentation,

bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) <-return bool

array_walk takes an array and a function F and modifies it by replacing every element x with F(x).

array array_map ( callback $callback , array $arr1 [, array $... ] )<-return array

array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.

array array_filter ( array $input [, callback $callback ] )<-return array

array_filter with function F, instead of transforming the elements, will remove any elements for which F(x) is not true

How to position absolute inside a div?

The absolute divs are taken out of the flow of the document so the containing div does not have any content except for the padding. Give #box a height to fill it out.

#box {
    background-color: #000;
    position: relative;
    padding: 10px;
    width: 220px;
    height:30px;
}

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

CodeIgniter : Unable to load the requested file:

I was getting this error in PyroCMS.

You can improve the error message in the Loader.php file that is in the code of the library.

Open the Loader.php file and find any calls to show_error. I replaced mine with the following:

show_error(sprintf("Unable to load the requested file: \"%s\" with instance title of \"%s\"", $_ci_file, $_ci_data['_ci_vars']['options']['instance_title']));

I was then able to see which file was causing the issues for me.

How to set the opacity/alpha of a UIImage?

Set the opacity of its view it is showed in.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0

Use this in an animation. You can change the alpha in an animation for an duration.

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
//Set alpha
[UIView commitAnimations];

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

One additional idea, mentioned here is to use a regular expression to check:

SELECT  foo 
FROM    bar
WHERE   REGEXP_LIKE (foo,'^[[:digit:]]+$');

The nice part is you do not need a separate PL/SQL function. The potentially problematic part is that a regular expression may not be the most efficient method for a large number of rows.

installing apache: no VCRUNTIME140.dll

Be sure you have C++ Redistributable for Visual Studio 2015 RC. Try to download the last version:

https://www.microsoft.com/en-us/download/details.aspx?id=52685

Obs: Credit to parsecer

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

MySQL Workbench Dark Theme

MySQL Workbench 8.0 Update

Based on Gunther's answer, it seems like in code_editor.xml they're planning to enable a dark mode at some point down the road. What was once fore-color has now been split into fore-color-light and fore-color-dark. Likewise with back-color.

Here's how to get a dark editor (not whole application theme) based on the Monokai colours provided graciously by elMestre:

<!-- 
dark-gray:         #282828;
brown-gray:        #49483E;
gray:              #888888;
light-gray:        #CCCCCC;
ghost-white:       #F8F8F0;
light-ghost-white: #F8F8F2;
yellow:            #E6DB74;
blue:              #66D9EF;
pink:              #F92672;
purple:            #AE81FF;
brown:             #75715E;
orange:            #FD971F;
light-orange:      #FFD569;
green:             #A6E22E;
sea-green:         #529B2F; 
-->

<style id="32" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" />   <!-- STYLE_DEFAULT       !BACKGROUND!   -->
<style id="33" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" />   <!-- STYLE_LINENUMBER                   -->
<style id= "0" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_DEFAULT                  -->

<style id= "1" fore-color-light="#999999" back-color-light="#282828" fore-color-dark="#999999" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id= "2" fore-color-light="#999999" back-color-light="#282828" fore-color-dark="#999999" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id= "3" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id= "4" fore-color-light="#66D9EF" back-color-light="#282828" fore-color-dark="#66D9EF" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id= "5" fore-color-light="#66D9EF" back-color-light="#282828" fore-color-dark="#66D9EF" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id= "6" fore-color-light="#AE81FF" back-color-light="#282828" fore-color-dark="#AE81FF" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id= "7" fore-color-light="#F92672" back-color-light="#282828" fore-color-dark="#F92672" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id= "8" fore-color-light="#F92672" back-color-light="#282828" fore-color-dark="#F92672" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id= "9" fore-color-light="#9B859D" back-color-light="#282828" fore-color-dark="#9B859D" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="10" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="11" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="12" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="13" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="14" fore-color-light="#F92672" back-color-light="#282828" fore-color-dark="#F92672" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="15" fore-color-light="#9B859D" back-color-light="#282828" fore-color-dark="#9B859D" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="16" fore-color-light="#DDDDDD" back-color-light="#282828" fore-color-dark="#DDDDDD" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="17" fore-color-light="#E6DB74" back-color-light="#282828" fore-color-dark="#E6DB74" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="18" fore-color-light="#529B2F" back-color-light="#282828" fore-color-dark="#529B2F" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="19" fore-color-light="#529B2F" back-color-light="#282828" fore-color-dark="#529B2F" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="20" fore-color-light="#529B2F" back-color-light="#282828" fore-color-dark="#529B2F" back-color-dark="#282828" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="21" fore-color-light="#66D9EF" back-color-light="#49483E" fore-color-dark="#66D9EF" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="22" fore-color-light="#909090" back-color-light="#49483E" fore-color-dark="#909090" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color-light="#999999" back-color-light="#49483E" fore-color-dark="#999999" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id="66" fore-color-light="#999999" back-color-light="#49483E" fore-color-dark="#999999" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id="67" fore-color-light="#DDDDDD" back-color-light="#49483E" fore-color-dark="#DDDDDD" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id="68" fore-color-light="#66D9EF" back-color-light="#49483E" fore-color-dark="#66D9EF" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id="69" fore-color-light="#66D9EF" back-color-light="#49483E" fore-color-dark="#66D9EF" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id="70" fore-color-light="#AE81FF" back-color-light="#49483E" fore-color-dark="#AE81FF" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id="71" fore-color-light="#F92672" back-color-light="#49483E" fore-color-dark="#F92672" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id="72" fore-color-light="#F92672" back-color-light="#49483E" fore-color-dark="#F92672" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id="73" fore-color-light="#9B859D" back-color-light="#49483E" fore-color-dark="#9B859D" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="74" fore-color-light="#DDDDDD" back-color-light="#49483E" fore-color-dark="#DDDDDD" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="75" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="76" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="77" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="78" fore-color-light="#F92672" back-color-light="#49483E" fore-color-dark="#F92672" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="79" fore-color-light="#9B859D" back-color-light="#49483E" fore-color-dark="#9B859D" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="80" fore-color-light="#DDDDDD" back-color-light="#49483E" fore-color-dark="#DDDDDD" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="81" fore-color-light="#E6DB74" back-color-light="#49483E" fore-color-dark="#E6DB74" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="82" fore-color-light="#529B2F" back-color-light="#49483E" fore-color-dark="#529B2F" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="83" fore-color-light="#529B2F" back-color-light="#49483E" fore-color-dark="#529B2F" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="84" fore-color-light="#529B2F" back-color-light="#49483E" fore-color-dark="#529B2F" back-color-dark="#49483E" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="85" fore-color-light="#66D9EF" back-color-light="#888888" fore-color-dark="#66D9EF" back-color-dark="#888888" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="86" fore-color-light="#AAAAAA" back-color-light="#888888" fore-color-dark="#AAAAAA" back-color-dark="#888888" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->  

Remember to paste all these styles inside of the <language name="SCLEX_MYSQL"> tag in data > code_editor.xml.

enter image description here

How to specify the bottom border of a <tr>?

You should define the style on the td element like so:

<html>
<head>
    <style type="text/css">
        .bb
        {
            border-bottom: solid 1px black;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td>
                Test 1
            </td>
        </tr>
        <tr>
            <td class="bb">
                Test 2
            </td>
        </tr>
    </table>
</body>
</html>

What is class="mb-0" in Bootstrap 4?

class="mb-0"

m - sets margin

b - sets bottom margin or padding

0 - sets 0 margin or padding


CSS class

.mb-0{
       margin-bottom: 0
     }

How to do constructor chaining in C#

This is best illustrated with an example. Imaging we have a class Person

public Person(string name) : this(name, string.Empty)
{
}

public Person(string name, string address) : this(name, address, string.Empty)
{
}

public Person(string name, string address, string postcode)
{
    this.Name = name;
    this.Address = address;
    this.Postcode = postcode;
}

So here we have a constructor which sets some properties, and uses constructor chaining to allow you to create the object with just a name, or just a name and address. If you create an instance with just a name this will send a default value, string.Empty through to the name and address, which then sends a default value for Postcode through to the final constructor.

In doing so you're reducing the amount of code you've written. Only one constructor actually has code in it, you're not repeating yourself, so, for example, if you change Name from a property to an internal field you need only change one constructor - if you'd set that property in all three constructors that would be three places to change it.

I keep getting "Uncaught SyntaxError: Unexpected token o"

Another hints for Unexpected token errors. There are two major differences between javascript objects and json:

  1. json data must be always quoted with double quotes.
  2. keys must be quoted

Correct JSON

 {
    "english": "bag",
    "kana": "kaban",
    "kanji": "K"
}

Error JSON 1

 {
    'english': 'bag',
    'kana': 'kaban',
    'kanji': 'K'
 }

Error JSON 2

 {
    english: "bag",
    kana: "kaban",
    kanji: "K"
}

Remark

This is not a direct answer for that question. But it's an answer for Unexpected token errors. So it may be help others who stumple upon that question.

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

Upper memory limit?

(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.

Edits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major. This is so if folks use it as template, it will provide an even better basis.

As others have pointed out, your MemoryError problem is most likely because you're attempting to read the entire contents of huge files into memory and then, on top of that, effectively doubling the amount of memory needed by creating a list of lists of the string values from each line.

Python's memory limits are determined by how much physical ram and virtual memory disk space your computer and operating system have available. Even if you don't use it all up and your program "works", using it may be impractical because it takes too long.

Anyway, the most obvious way to avoid that is to process each file a single line at a time, which means you have to do the processing incrementally.

To accomplish this, a list of running totals for each of the fields is kept. When that is finished, the average value of each field can be calculated by dividing the corresponding total value by the count of total lines read. Once that is done, these averages can be printed out and some written to one of the output files. I've also made a conscious effort to use very descriptive variable names to try to make it understandable.

try:
    from itertools import izip_longest
except ImportError:    # Python 3
    from itertools import zip_longest as izip_longest

GROUP_SIZE = 4
input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt",
                    "A2_B1_100000.txt"]
file_write = open("average_generations.txt", 'w')
mutation_average = open("mutation_average", 'w')  # left in, but nothing written

for file_name in input_file_names:
    with open(file_name, 'r') as input_file:
        print('processing file: {}'.format(file_name))

        totals = []
        for count, fields in enumerate((line.split('\t') for line in input_file), 1):
            totals = [sum(values) for values in
                        izip_longest(totals, map(float, fields), fillvalue=0)]
        averages = [total/count for total in totals]

        for print_counter, average in enumerate(averages):
            print('  {:9.4f}'.format(average))
            if print_counter % GROUP_SIZE == 0:
                file_write.write(str(average)+'\n')

file_write.write('\n')
file_write.close()
mutation_average.close()

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Here the packaging is jar type, hence you need to use manifest plugin, in order to add dependencies into the Manifest.mf

The problem here is that maven could find the dependencies in pom file and compile the source code and create the output jar. But when executing the jar, manifest.mf file contains no details of dependencies. Hence you got this error. This is a case of classpath errors.

Here you can find the details on how to do it.

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

Reading values from DataTable

For VB.Net is

        Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "database path")
        Dim cmd As New OleDb.OleDbCommand
        Dim dt As New DataTable
        Dim da As New OleDb.OleDbDataAdapter
        con.Open()
        cmd.Connection = con
        cmd.CommandText = sql
        da.SelectCommand = cmd

        da.Fill(dt)

        For i As Integer = 0 To dt.Rows.Count
            someVar = dt.Rows(i)("fieldName")
        Next

Regex matching beginning AND end strings

Scanner scanner = new Scanner(System.in);
String part = scanner.nextLine();
String line = scanner.nextLine();

String temp = "\\b" + part +"|"+ part + "\\b";
Pattern pattern = Pattern.compile(temp.toLowerCase());
Matcher matcher = pattern.matcher(line.toLowerCase());

System.out.println(matcher.find() ? "YES":"NO");

If you need to determine if any of the words of this text start or end with the sequence. you can use this regex \bsubstring|substring\b anythingsubstring substringanything anythingsubstringanything

VSCode cannot find module '@angular/core' or any other modules

Try this, it worked for me:

npm i --save @angular/platform-server  

Then reopen VS code

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

How can I set my Cygwin PATH to find javac?

To bring more prominence to the useful comment by @johanvdw:

If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/" somewhere in the file.

When Cygwin starts, it'll search directories in PATH and this one for executable files to run.

MongoDB - admin user not authorized

This may be because you havent set noAuth=true in mongodb.conf

# Turn on/off security.  Off is currently the default
noauth = true
#auth = true

After setting this restart the service using

service mongod restart

There is an error in XML document (1, 41)

Agreed with the answer from sll, but experienced another hurdle which was having specified a namespace in the attributes, when receiving the return xml that namespace wasn't included and thus failed finding the class.

i had to find a workaround to specifying the namespace in the attribute and it worked.

ie.

[Serializable()]
    [XmlRoot("Patient", Namespace = "http://www.xxxx.org/TargetNamespace")]
    public class Patient

generated

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xxxx.org/TargetNamespace">

but I had to change it to

[Serializable()]
[XmlRoot("Patient")]
public class Patient

which generated to

<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

This solved my problem, hope it helps someone else.

eval command in Bash and its typical uses

You asked about typical uses.

One common complaint about shell scripting is that you (allegedly) can't pass by reference to get values back out of functions.

But actually, via "eval", you can pass by reference. The callee can pass back a list of variable assignments to be evaluated by the caller. It is pass by reference because the caller can allowed to specify the name(s) of the result variable(s) - see example below. Error results can be passed back standard names like errno and errstr.

Here is an example of passing by reference in bash:

#!/bin/bash
isint()
{
    re='^[-]?[0-9]+$'
    [[ $1 =~ $re ]]
}

#args 1: name of result variable, 2: first addend, 3: second addend 
iadd()
{
    if isint ${2} && isint ${3} ; then
        echo "$1=$((${2}+${3}));errno=0"
        return 0
    else
        echo "errstr=\"Error: non-integer argument to iadd $*\" ; errno=329"
        return 1
    fi
}

var=1
echo "[1] var=$var"

eval $(iadd var A B)
if [[ $errno -ne 0 ]]; then
    echo "errstr=$errstr"
    echo "errno=$errno"
fi
echo "[2] var=$var (unchanged after error)"

eval $(iadd var $var 1)
if [[ $errno -ne 0 ]]; then
    echo "errstr=$errstr"
    echo "errno=$errno"
fi  
echo "[3] var=$var (successfully changed)"

The output looks like this:

[1] var=1
errstr=Error: non-integer argument to iadd var A B
errno=329
[2] var=1 (unchanged after error)
[3] var=2 (successfully changed)

There is almost unlimited band width in that text output! And there are more possibilities if the multiple output lines are used: e.g., the first line could be used for variable assignments, the second for continuous 'stream of thought', but that's beyond the scope of this post.

Java - get index of key in HashMap?

Posting this as an equally viable alternative to @Binil Thomas's answer - tried to add it as a comment, but was not convinced of the readability of it all.

int index = 0;

for (Object key : map.keySet()) {
   Object value = map.get(key);
   ++index;
}

Probably doesn't help the original question poster since this is the literal situation they were trying to avoid, but may aid others searching for an easy answer.

Add new field to every document in a MongoDB collection

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

Check out this example:

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

EDIT:

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

db.your_collection.update(
  {},
  { $set: {"new_field": 1} },
  false,
  true
)

EDIT:

In the above example last 2 fields false, true specifies the upsert and multi flags.

Upsert: If set to true, creates a new document when no document matches the query criteria.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}) 

git: fatal: I don't handle protocol '??http'

I simply added 5 "SPACE"s between clone and the url:

  git clone     ?https://<PATH>/<TO>/<GIT_REPO>.git

and it works!

SQL Server add auto increment primary key to existing table

Try something like this (on a test table first):

USE your_database_name
GO
WHILE (SELECT COUNT(*) FROM your_table WHERE your_id_field IS NULL) > 0
BEGIN
    SET ROWCOUNT 1
    UPDATE your_table SET your_id_field = MAX(your_id_field)+1
END
PRINT 'ALL DONE'

I have not tested this at all, so be careful!

Printing out a linked list using toString

I do it the following way:

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

What does auto do in margin:0 auto?

From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

finished with non zero exit value

I have faced the same error while compiling. I tried all the methods here but failed only one thing worked but it takes a lot of time. by running this code on CMD to debug my app and shows me the missing tag in my XML layout.

gradle processDebugResources --debug

The best approach is to analyze the error not just ignoring it.

To run this code I installed Java JDK and then set Environment Variable: for JAVA_HOME and Gradle.

for gradle

C:\Program Files\Android\Android Studio\gradle\gradle-4.6\bin

for java

JAVA_HOME=C:\Program Files\Java\jre1.8.0_191

jquery json to string?

You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.

Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.

In a unix shell, how to get yesterday's date into a variable?

For Hp-UX only below command worked for me:

TZ=aaa24 date +%Y%m%d

you can use it as :

ydate=`TZ=aaa24 date +%Y%m%d`

echo $ydate

Log record changes in SQL server in an audit table

I know this is old, but maybe this will help someone else.

Do not log "new" values. Your existing table, GUESTS, has the new values. You'll have double entry of data, plus your DB size will grow way too fast that way.

I cleaned this up and minimized it for this example, but here is the tables you'd need for logging off changes:

CREATE TABLE GUESTS (
      GuestID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

CREATE TABLE GUESTS_LOG (
      GuestLogID INT IDENTITY(1,1) PRIMARY KEY, 
      GuestID INT, 
      GuestName VARCHAR(50), 
      ModifiedBy INT, 
      ModifiedOn DATETIME
)

When a value changes in the GUESTS table (ex: Guest name), simply log off that entire row of data, as-is, to your Log/Audit table using the Trigger. Your GUESTS table has current data, the Log/Audit table has the old data.

Then use a select statement to get data from both tables:

SELECT 0 AS 'GuestLogID', GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS] WHERE GuestID = 1
UNION
SELECT GuestLogID, GuestID, GuestName, ModifiedBy, ModifiedOn FROM [GUESTS_LOG] WHERE GuestID = 1
ORDER BY ModifiedOn ASC

Your data will come out with what the table looked like, from Oldest to Newest, with the first row being what was created & the last row being the current data. You can see exactly what changed, who changed it, and when they changed it.

Optionally, I used to have a function that looped through the RecordSet (in Classic ASP), and only displayed what values had changed on the web page. It made for a GREAT audit trail so that users could see what had changed over time.

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

Find number of decimal places in decimal value regardless of culture

I use the following mechanism in my code

  public static int GetDecimalLength(string tempValue)
    {
        int decimalLength = 0;
        if (tempValue.Contains('.') || tempValue.Contains(','))
        {
            char[] separator = new char[] { '.', ',' };
            string[] tempstring = tempValue.Split(separator);

            decimalLength = tempstring[1].Length;
        }
        return decimalLength;
    }

decimal input=3.376; var instring=input.ToString();

call GetDecimalLength(instring)

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

PHP 8 or newer:

Use the str_starts_with function:

str_starts_with('http://www.google.com', 'http')

PHP 7 or older:

Use the substr function to return a part of a string.

substr( $string_n, 0, 4 ) === "http"

If you're trying to make sure it's not another protocol. I'd use http:// instead, since https would also match, and other things such as http-protocol.com.

substr( $string_n, 0, 7 ) === "http://"

And in general:

substr($string, 0, strlen($query)) === $query

How do I set a variable to the output of a command in Bash?

Just to be different:

MOREF=$(sudo run command against $VAR1 | grep name | cut -c7-)

Modulo operation with negative numbers

Can a modulus be negative?

% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1  

The modulo OP wanted is a classic Euclidean modulo, not %.

I was expecting a positive result every time.

To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

modulo_Euclidean( 7,  3) -->  1  
modulo_Euclidean( 7, -3) -->  1  
modulo_Euclidean(-7,  3) -->  2  
modulo_Euclidean(-7, -3) -->  2   

How to scroll to top of the page in AngularJS?

use: $anchorScroll();

with $anchorScroll property

scrollable div inside container

Is this what you are wanting?

_x000D_
_x000D_
<body>_x000D_
  <div id="div1" style="height: 500px;">_x000D_
    <div id="div2" style="height: inherit; overflow: auto; border:1px solid red;">_x000D_
      <div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/fMs67/1/

Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

This one will give you date no time:

=FormatDateTime(DateAdd("m", -1, DateSerial(Year(Today()), Month(Today()), 1)), 
DateFormat.ShortDate)

This one will give you datetime:

=dateadd("m",-1,dateserial(year(Today),month(Today),1)) 

preferredStatusBarStyle isn't called

My app used all three: UINavigationController, UISplitViewController, UITabBarController, thus these all seem to take control over the status bar and will cause preferedStatusBarStyle to not be called for their children. To override this behavior you can create an extension like the rest of the answers have mentioned. Here is an extension for all three, in Swift 4. Wish Apple was more clear about this sort of stuff.

extension UINavigationController {
    open override var childViewControllerForStatusBarStyle: UIViewController? {
        return self.topViewController
    }

    open override var childViewControllerForStatusBarHidden: UIViewController? {
        return self.topViewController
    }
}

extension UITabBarController {
    open override var childViewControllerForStatusBarStyle: UIViewController? {
        return self.childViewControllers.first
    }

    open override var childViewControllerForStatusBarHidden: UIViewController? {
        return self.childViewControllers.first
    }
}

extension UISplitViewController {
    open override var childViewControllerForStatusBarStyle: UIViewController? {
        return self.childViewControllers.first
    }

    open override var childViewControllerForStatusBarHidden: UIViewController? {
        return self.childViewControllers.first
    }
}

Edit: Update for Swift 4.2 API changes

extension UINavigationController {
    open override var childForStatusBarStyle: UIViewController? {
        return self.topViewController
    }

    open override var childForStatusBarHidden: UIViewController? {
        return self.topViewController
    }
}

extension UITabBarController {
    open override var childForStatusBarStyle: UIViewController? {
        return self.children.first
    }

    open override var childForStatusBarHidden: UIViewController? {
        return self.children.first
    }
}

extension UISplitViewController {
    open override var childForStatusBarStyle: UIViewController? {
        return self.children.first
    }

    open override var childForStatusBarHidden: UIViewController? {
        return self.children.first
    }
}

SQL: how to select a single id ("row") that meets multiple criteria from a single column

This question is some years old but i came via a duplicate to it. I want to suggest a more general solution too. If you know you always have a fixed number of ancestors you can use some self joins as already suggested in the answers. If you want a generic approach go on reading.

What you need here is called Quotient in relational Algebra. The Quotient is more or less the reversal of the Cartesian Product (or Cross Join in SQL).

Let's say your ancestor set A is (i use a table notation here, i think this is better for understanding)

ancestry
-----------
'England'
'France'
'Germany'

and your user set U is

user_id
--------
   1
   2
   3

The cartesian product C=AxU is then:

user_id  |  ancestry
---------+-----------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'
   2     | 'England'
   2     | 'France'
   2     | 'Germany'
   3     | 'England'
   3     | 'France'
   3     | 'Germany'

If you calculate the set quotient U=C/A then you get

user_id
--------
   1
   2
   3

If you redo the cartesian product UXA you will get C again. But note that for a set T, (T/A)xA will not necessarily reproduce T. For example, if T is

user_id  |  ancestry
---------+-----------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'
   2     | 'England'
   2     | 'France'

then (T/A) is

user_id
--------
   1

(T/A)xA will then be

user_id  |  ancestry
---------+------------
   1     | 'England'
   1     | 'France'
   1     | 'Germany'

Note that the records for user_id=2 have been eliminated by the Quotient and Cartesian Product operations.

Your question is: Which user_id has ancestors from all countries in your ancestor set? In other words you want U=T/A where T is your original set (or your table).

To implement the quotient in SQL you have to do 4 steps:

  1. Create the Cartesian Product of your ancestry set and the set of all user_ids.
  2. Find all records in the Cartesian Product which have no partner in the original set (Left Join)
  3. Extract the user_ids from the resultset of 2)
  4. Return all user_ids from the original set which are not included in the result set of 3)

So let's do it step by step. I will use TSQL syntax (Microsoft SQL server) but it should easily be adaptable to other DBMS. As a name for the table (user_id, ancestry) i choose ancestor

CREATE TABLE ancestry_set (ancestry nvarchar(25))
INSERT INTO ancestry_set (ancestry) VALUES ('England')
INSERT INTO ancestry_set (ancestry) VALUES ('France')
INSERT INTO ancestry_set (ancestry) VALUES ('Germany')

CREATE TABLE ancestor ([user_id] int, ancestry nvarchar(25))
INSERT INTO ancestor ([user_id],ancestry) VALUES (1,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(1,'Ireland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(2,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(3,'Poland')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'England')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(4,'Germany')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'France')
INSERT INTO ancestor ([user_id],ancestry) VALUES(5,'Germany')

1) Create the Cartesian Product of your ancestry set and the set of all user_ids.

SELECT a.[user_id],s.ancestry
FROM ancestor a, ancestry_set s
GROUP BY a.[user_id],s.ancestry

2) Find all records in the Cartesian Product which have no partner in the original set (Left Join) and

3) Extract the user_ids from the resultset of 2)

SELECT DISTINCT cp.[user_id]
FROM (SELECT a.[user_id],s.ancestry
      FROM ancestor a, ancestry_set s
      GROUP BY a.[user_id],s.ancestry) cp
   LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
WHERE a.[user_id] is null

4) Return all user_ids from the original set which are not included in the result set of 3)

SELECT DISTINCT [user_id]
FROM ancestor
WHERE [user_id] NOT IN (
   SELECT DISTINCT cp.[user_id]
   FROM (SELECT a.[user_id],s.ancestry
         FROM ancestor a, ancestry_set s
         GROUP BY a.[user_id],s.ancestry) cp
   LEFT JOIN ancestor a ON cp.[user_id]=a.[user_id] AND cp.ancestry=a.ancestry
   WHERE a.[user_id] is null
   )

Difference between using gradlew and gradle

The difference lies in the fact that ./gradlew indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle and then invoke gradle using the gradle command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.

Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.

Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable

Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html

Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk

Finding square root without using sqrt function?

As I found this question is old and have many answers but I have an answer which is simple and working great..

#define EPSILON 0.0000001 // least minimum value for comparison
double SquareRoot(double _val) {
    double low = 0; 
    double high = _val;
    double mid = 0; 

    while (high - low > EPSILON) {
            mid = low + (high - low) / 2; // finding mid value
            if (mid*mid > _val) {
                high = mid;
            } else {
                low = mid;
            }    
    }   
    return mid;
}

I hope it will be helpful for future users.

How to load image (and other assets) in Angular an project?

for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.

Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.

Installed Java 7 on Mac OS X but Terminal is still using version 6

Installing through distributed JDK DMG from the Oracle site auto-updates everything for me. I have seen (in El Capitan) updating through System Preferences > Java do updates but that do not reflect to command line. Installing through DMG does the job.

Converting String to "Character" array in Java

chaining is always best :D

String str = "somethingPutHere";
Character[] c = ArrayUtils.toObject(str.toCharArray());

Catching multiple exception types in one catch block

As of PHP 7.1,

catch( AError | BError $e )
{
    handler1( $e )
}

interestingly, you can also:

catch( AError | BError $e )
{
    handler1( $e )
} catch (CError $e){
    handler2($e);
} catch(Exception $e){
    handler3($e);
}

and in earlier versions of PHP:

catch(Exception $ex){
    if($ex instanceof AError){
        //handle a AError
    } elseif($ex instanceof BError){
        //handle a BError
    } else {
       throw $ex;//an unknown exception occured, throw it further
    }
}

How to open a link in new tab (chrome) using Selenium WebDriver?

Selenium 4 is already included this feature now, you can directly 
open new Tab or new Window with any URL. 

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver(options);

driver.get("www.Url1.com");     
//  below code will open Tab for you as well as switch the control to new Tab
driver.switchTo().newWindow(WindowType.TAB);

// below code will navigate you to your desirable Url 
driver.get("www.Url2.com");

download Maven dependencies, this is what I downloaded - 

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.7.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency> 

    you can refer: https://codoid.com/selenium-4-0-command-to-open-new-window-tab/

    watch video : https://www.youtube.com/watch?v=7SpCMkUKq-Y&t=8s

google out for - WebDriverManager selenium 4

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

SQL how to make null values come last when sorting ascending

Solution using the "case" is universal, but then do not use the indexes.

order by case when MyDate is null then 1 else 0 end, MyDate

In my case, I needed performance.

 SELECT smoneCol1,someCol2  
 FROM someSch.someTab
 WHERE someCol2 = 2101 and ( someCol1 IS NULL ) 
  UNION   
 SELECT smoneCol1,someCol2
 FROM someSch.someTab
 WHERE someCol2 = 2101 and (  someCol1 IS NOT NULL)  

DirectX SDK (June 2010) Installation Problems: Error Code S1023

Here is the official answer from Microsoft: http://blogs.msdn.com/b/chuckw/archive/2011/12/09/known-issue-directx-sdk-june-2010-setup-and-the-s1023-error.aspx

Summary if you'd rather not click through:

  1. Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:

    MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}

    MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}

  2. Install the DirectX SDK (June 2010)

  3. Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB2565063 with a security fix.

Windows SDK: The Windows SDK 7.1 has exactly the same issue as noted in KB 2717426.

error: Your local changes to the following files would be overwritten by checkout

I encountered the same problem and solved it by

git checkout -f branch

Well, be careful with the -f switch. You will lose any uncommitted changes if you use the -f switch. While there may be some use cases where it is helpful to use -f, in most cases, you may want to stash your changes and then switch branches. The stashing procedure is explained above.

Reference excel worksheet by name?

The best way is to create a variable of type Worksheet, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet.

This will help you avoid bugs that will eventually show up when your program grows in size.

For example something like Range("A1:C10").Sort Key1:=Range("A2") is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")... and find out that it still doesn't work.

Here is the correct way:

Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")

Turning off auto indent when pasting text into vim

Stick this in your ~/.vimrc and be happy:

" enables :Paste to just do what you want
command Paste execute 'set noai | insert | set ai'

Edit: on reflection, :r !cat is a far better approach since it's short, semantic, and requires no custom vimrc. Use that instead!

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

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

Is the URL that this code is making accessible in the browser?

http://" + Request.ServerVariables["HTTP_HOST"] + Request.ApplicationPath + "/PageDetails.aspx?ModuleID=" + ID

First thing you need to verify is that the URL you are making is correct. Then check in the browser to see if it is browsing. then use Fiddler tool to check what is passing over the network. It may be that URL that is being called through code is wrongly escaped.

Then check for firewall related issues.

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

PHP String to Float

If you need to handle values that cannot be converted separately, you can use this method:

try {
    $valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
    // bail here if you need to
}

Implementing multiple interfaces with Java - is there a way to delegate?

There is one way to implement multiple interface.

Just extend one interface from another or create interface that extends predefined interface Ex:

public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces

public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps

iOS 9 not opening Instagram app with URL SCHEME

Apple changed the canOpenURL method on iOS 9. Apps which are checking for URL Schemes on iOS 9 and iOS 10 have to declare these Schemes as it is submitted to Apple.

Easy way to pull latest of all git submodules

Here is the command-line to pull from all of your git repositories whether they're or not submodules:

ROOT=$(git rev-parse --show-toplevel 2> /dev/null)
find "$ROOT" -name .git -type d -execdir git pull -v ';'

If you running it in your top git repository, you can replace "$ROOT" into ..

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

How to add a right button to a UINavigationController?

You can try

self.navigationBar.topItem.rightBarButtonItem = anotherButton;

How can I see the entire HTTP request that's being sent by my Python application?

A simple method: enable logging in recent versions of Requests (1.x and higher.)

Requests uses the http.client and logging module configuration to control logging verbosity, as described here.

Demonstration

Code excerpted from the linked documentation:

import requests
import logging

# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

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

Example Output

$ python requests-logging.py 
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226

Loop backwards using indices in Python?

for i in range(100, -1, -1)

and some slightly longer (and slower) solution:

for i in reversed(range(101))

for i in range(101)[::-1]

C++ String Concatenation operator<<

First of all it is unclear what type name has. If it has the type std::string then instead of

string nametext;
nametext = "Your name is" << name;

you should write

std::string nametext = "Your name is " + name;

where operator + serves to concatenate strings.

If name is a character array then you may not use operator + for two character arrays (the string literal is also a character array), because character arrays in expressions are implicitly converted to pointers by the compiler. In this case you could write

std::string nametext( "Your name is " );
nametext.append( name );

or

std::string nametext( "Your name is " );
nametext += name;

Get column index from label in a data frame

Use t function:

t(colnames(df))

     [,1]   [,2]   [,3]   [,4]   [,5]   [,6]  
[1,] "var1" "var2" "var3" "var4" "var5" "var6"

How to call a method after bean initialization is complete?

To further clear any confusion about the two approach i.e use of

  1. @PostConstruct and
  2. init-method="init"

From personal experience, I realized that using (1) only works in a servlet container, while (2) works in any environment, even in desktop applications. So, if you would be using Spring in a standalone application, you would have to use (2) to carry out that "call this method after initialization.

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

Check existence of input argument in a Bash shell script

If you'd like to check if the argument exists, you can check if the # of arguments is greater than or equal to your target argument number.

The following script demonstrates how this works

test.sh

#!/usr/bin/env bash

if [ $# -ge 3 ]
then
  echo script has at least 3 arguments
fi

produces the following output

$ ./test.sh
~
$ ./test.sh 1
~
$ ./test.sh 1 2
~
$ ./test.sh 1 2 3
script has at least 3 arguments
$ ./test.sh 1 2 3 4
script has at least 3 arguments

How can I check if a jQuery plugin is loaded?

This sort of approach should work.

var plugin_exists = true;

try {
  // some code that requires that plugin here
} catch(err) {
  plugin_exists = false;
}

What are .NET Assemblies?

In addition to the accepted answer, I want to give you an example!

For instance, we all use

System.Console.WriteLine()

But Where is the code for System.Console.WriteLine!?
which is the code that actually puts the text on the console?

If you look at the first page of the documentation for the Console class, you‘ll see near the top the following: Assembly: mscorlib (in mscorlib.dll) This indicates that the code for the Console class is located in an assem-bly named mscorlib. An assembly can consist of multiple files, but in this case it‘s only one file, which is the dynamic link library mscorlib.dll.

The mscorlib.dll file is very important in .NET, It is the main DLL for class libraries in .NET, and it contains all the basic .NET classes and structures.

if you know C or C++, generally you need a #include directive at the top that references a header file. The include file provides function prototypes to the compiler. on the contrast The C# compiler does not need header files. During compilation, the C# compiler access the mscorlib.dll file directly and obtains information from metadata in that file concerning all the classes and other types defined therein.

The C# compiler is able to establish that mscorlib.dll does indeed contain a class named Console in a namespace named System with a method named WriteLine that accepts a single argument of type string.

The C# compiler can determine that the WriteLine call is valid, and the compiler establishes a reference to the mscorlib assembly in the executable.

by default The C# compiler will access mscorlib.dll, but for other DLLs, you‘ll need to tell the compiler the assembly in which the classes are located. These are known as references.

I hope that it's clear now!

From DotNetBookZero Charles pitzold

How to sign an android apk file

The manual is clear enough. Please specify what part you get stuck with after you work through it, I'd suggest:

https://developer.android.com/studio/publish/app-signing.html

Okay, a small overview without reference or eclipse around, so leave some space for errors, but it works like this

  • Open your project in eclipse
  • Press right-mouse - > tools (android tools?) - > export signed application (apk?)
  • Go through the wizard:
  • Make a new key-store. remember that password
  • Sign your app
  • Save it etc.

Also, from the link:

Compile and sign with Eclipse ADT

If you are using Eclipse with the ADT plugin, you can use the Export Wizard to export a signed .apk (and even create a new keystore, if necessary). The Export Wizard performs all the interaction with the Keytool and Jarsigner for you, which allows you to sign the package using a GUI instead of performing the manual procedures to compile, sign, and align, as discussed above. Once the wizard has compiled and signed your package, it will also perform package alignment with zip align. Because the Export Wizard uses both Keytool and Jarsigner, you should ensure that they are accessible on your computer, as described above in the Basic Setup for Signing.

To create a signed and aligned .apk in Eclipse:

  1. Select the project in the Package Explorer and select File > Export.
  2. Open the Android folder, select Export Android Application, and click Next.

    The Export Android Application wizard now starts, which will guide you through the process of signing your application, including steps for selecting the private key with which to sign the .apk (or creating a new keystore and private key).

  3. Complete the Export Wizard and your application will be compiled, signed, aligned, and ready for distribution.

How do you check if a JavaScript Object is a DOM Object?

if you are using jQuery, try this

$('<div>').is('*') // true
$({tagName: 'a'}).is('*') // false
$({}).is('*') // false
$([]).is('*') // false
$(0).is('*') // false
$(NaN).is('*') // false

Backbone.js fetch with parameters

You can also set processData to true:

collection.fetch({ 
    data: { page: 1 },
    processData: true
});

Jquery will auto process data object into param string,

but in Backbone.sync function, Backbone turn the processData off because Backbone will use other method to process data in POST,UPDATE...

in Backbone source:

if (params.type !== 'GET' && !Backbone.emulateJSON) {
    params.processData = false;
}

efficient way to implement paging

Try using

FROM [TableX]
ORDER BY [FieldX]
OFFSET 500 ROWS
FETCH NEXT 100 ROWS ONLY

to get the rows from 501 to 600 in the SQL server, without loading them in memory. Note that this syntax has become available with SQL Server 2012 only

How can I extract audio from video with ffmpeg?

To extract the audio stream without re-encoding:

ffmpeg -i input-video.avi -vn -acodec copy output-audio.aac
  • -vn is no video.
  • -acodec copy says use the same audio stream that's already in there.

Read the output to see what codec it is, to set the right filename extension.

DECODE( ) function in SQL Server

In my Case I used it in a lot of places first example if you have 2 values for select statement like gender (Male or Female) then use the following statement:

SELECT CASE Gender WHEN 'Male' THEN 1 ELSE 2 END AS Gender

If there is more than one condition like nationalities you can use it as the following statement:

SELECT CASE Nationality 
WHEN 'AMERICAN'   THEN 1 
WHEN 'BRITISH'   THEN 2
WHEN 'GERMAN'    THEN 3 
WHEN 'EGYPT'     THEN 4 
WHEN 'PALESTINE' THEN 5 
ELSE 6 END AS Nationality 

Remove duplicate values from JS array

The most concise way to remove duplicates from an array using native javascript functions is to use a sequence like below:

vals.sort().reduce(function(a, b){ if (b != a[0]) a.unshift(b); return a }, [])

there's no need for slice nor indexOf within the reduce function, like i've seen in other examples! it makes sense to use it along with a filter function though:

vals.filter(function(v, i, a){ return i == a.indexOf(v) })

Yet another ES6(2015) way of doing this that already works on a few browsers is:

Array.from(new Set(vals))

or even using the spread operator:

[...new Set(vals)]

cheers!

Convert NVARCHAR to DATETIME in SQL Server 2008

As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

|                     YOUR_DT |             SQL2008 |
|-----------------------------|---------------------|
|         2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
|    2013-08-29 13:55:48 blah |              (null) |
| 2013-08-29 13:55:48 rubbish |              (null) |

SELECT
  [Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
                        THEN convert(datetime,[Your_Dt])
                        ELSE NULL
                     END
            ) AS ca1 (dt_converted)
;

Notes:

You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'

For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison

declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'

select
  FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008

|             SQL2012 |             SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 | 

Driver executable must be set by the webdriver.ie.driver system property

  1. You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

  2. Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

    File file = new File("C:/Selenium/iexploredriver.exe");
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    WebDriver driver = new InternetExplorerDriver();
    

Basically, you have to set this property before you initialize driver

how to convert a string date to date format in oracle10g

You need to use the TO_DATE function.

SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;

How to execute shell command in Javascript

If you are using npm you can use the shelljs package

To install: npm install [-g] shelljs

var shell = require('shelljs');
shell.ls('*.js').forEach(function (file) {
// do something
});

See more: https://www.npmjs.com/package/shelljs

Configure Log4Net in web application

I also had the similar issue. Logs were not creating.

Please check logger attribute name should match with your LogManager.GetLogger("name")

<logger name="Mylog">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>



private static readonly ILog Log = LogManager.GetLogger("Mylog");

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

In some cases, this might happen when:

obj = new obj();
...
obj.Dispose();  // <-----------------    Incorrect disposal causes it
obj.abc...

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

What is __main__.py?

Often, a Python program is run by naming a .py file on the command line:

$ python my_program.py

You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn't come from a __main__.py file. It can, but it usually doesn't. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a __main__.py file.

Generate a unique id

If you want to use sha-256 (guid would be faster) then you would need to do something like

SHA256 shaAlgorithm = new SHA256Managed();
byte[] shaDigest = shaAlgorithm.ComputeHash(ASCIIEncoding.ASCII.GetBytes(url));
return BitConverter.ToString(shaDigest);

Of course, it doesn't have to ascii and it can be any other kind of hashing algorithm as well

Import Excel to Datagridview

try the following program

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.DataSet DtSet;
        System.Data.OleDb.OleDbDataAdapter MyCommand;
        MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        MyCommand.TableMappings.Add("Table", "Net-informations.com");
        DtSet = new System.Data.DataSet();
        MyCommand.Fill(DtSet);
        dataGridView1.DataSource = DtSet.Tables[0];
        MyConnection.Close();
    }
}
} 

Using Google Translate in C#

Google is going to shut the translate API down by the end of 2011, so you should be looking at the alternatives!

Can you nest html forms?

Even if you could get it to work in one browser, there's no guarantee that it would work the same in all browsers. So while you might be able to get it to work some of the time, you certainly wouldn't be able to get it to work all of the time.

What is path of JDK on Mac ?

The location has changed from Java 6 (provided by Apple) to Java 7 and onwards (provided by Oracle). The best generic way to find this out is to run

/usr/libexec/java_home

This is the natively supported way to find out both the path to the default Java installation as well as all alternative ones present.

If you check out its help text (java_home -h), you'll see that you can use this command to reliably start a Java program on OS X (java_home --exec ...), with the ability to explicitly specify the desired Java version and architecture, or even request the user to install it if missing.

A more pedestrian approach, but one which will help you trace specifically which Java installation the command java resolves into, goes like this:

  1. run

    which java
    
  2. if that gives you something like /usr/bin/java, which is a symbolic link to the real location, run

    ls -l `which java`
    

    On my system, this outputs

    /usr/bin/java -> /Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java
    

    and therefrom you can read the Java home directory;

  3. if usr/bin/java points to another symbolic link, recursively apply the same approach with

    ls -l <whatever the /usr/bin/java symlink points to>
    

An important variation is the setup you get if you start by installing Apple's Java and later install Oracle's. In that case Step 2 above will give you

/usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Commands/java

and that particular java binary is a stub which will resolve the actual java command to call by consulting the JAVA_HOME environment variable and, if it's not set or doesn't point to a Java home directory, will fall back to calling java_home. It is important to have this in mind when debugging your setup.

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

Using curl to upload POST data with files

You need to use the -F option:
-F/--form <name=content> Specify HTTP multipart POST data (H)

Try this:

curl \
  -F "userid=1" \
  -F "filecomment=This is an image file" \
  -F "image=@/home/user1/Desktop/test.jpg" \
  localhost/uploader.php

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

Using "margin: 0 auto;" in Internet Explorer 8

Form controls are replaced elements in CSS.

10.3.4 Block-level, replaced elements in normal flow

The used value of 'width' is determined as for inline replaced elements. Then the rules for non-replaced block-level elements are applied to determine the margins.

So the form control should not be stretched to 100% width.

However, it should be centered. It looks like an ordinary bug in IE8. It centers the element if you set specific width:

<input type="submit" style="display: block; width:100px; margin: 0 auto;" />

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

jQuery: Slide left and slide right

If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations

For you, blindLeftToggle and blindRightToggle is the appropriate choice.

http://jsfiddle.net/ARTsinn/65QsU/

How to fix java.net.SocketException: Broken pipe?

This is caused by:

  • most usually, writing to a connection when the other end has already closed it;
  • less usually, the peer closing the connection without reading all the data that is already pending at his end.

So in both cases you have a poorly defined or implemented application protocol.

There is a third reason which I will not document here but which involves the peer taking deliberate action to reset rather than properly close the connection.

How do I list all tables in all databases in SQL Server in a single result set?

I think the common approach is to SELECT * FROM INFORMATION_SCHEMA.TABLES for each database using sp_MSforeachdb

I created a snippet in VS Code that I think it might be helpful.

Query

IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;
SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;
TRUNCATE TABLE #alltables;
EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';
SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%<TABLE_NAME_TO_SEARCH>%';
GO 

Snippet

{
    "List all tables": {
        "prefix": "sqlListTable",
        "body": [
            "IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;",
            "SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;",
            "TRUNCATE TABLE #alltables;",
            "EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';",
            "SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%$0%';",
            "GO"
        ]
    }
}

Android Color Picker

I know the question is old, but if someone is looking for a great new android color picker that use material design I have forked an great project from github and made a simple-to-use android color picker dialog.

This is the project: Android Color Picker

Android Color Picker dialog

enter image description here

HOW TO USE IT

Adding the library to your project

The aar artifact is available at the jcenter repository. Declare the repository and the dependency in your build.gradle.

(root)

repositories {
    jcenter()
}

(module)

dependencies {
    compile 'com.pes.materialcolorpicker:library:1.0.2'
}

Use the library

Create a color picker dialog object

final ColorPicker cp = new ColorPicker(MainActivity.this, defaultColorR, defaultColorG, defaultColorB);

defaultColorR, defaultColorG, defaultColorB are 3 integer ( value 0-255) for the initialization of the color picker with your custom color value. If you don't want to start with a color set them to 0 or use only the first argument

Then show the dialog (when & where you want) and save the selected color

/* Show color picker dialog */
cp.show();

/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button)cp.findViewById(R.id.okColorButton);

okColor.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            
        /* You can get single channel (value 0-255) */
        selectedColorR = cp.getRed();
        selectedColorG = cp.getGreen();
        selectedColorB = cp.getBlue();
            
        /* Or the android RGB Color (see the android Color class reference) */
        selectedColorRGB = cp.getColor();

        cp.dismiss();
    }
});

That's all :)

how to clear the screen in python

If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do

import os
os.system('cls')  # on windows

or

os.system('clear')  # on linux / os x

MySQL: How to allow remote connection to mysql

If your MySQL server process is listening on 127.0.0.1 or ::1 only then you will not be able to connect remotely. If you have a bind-address setting in /etc/my.cnf this might be the source of the problem.

You will also have to add privileges for a non-localhost user as well.

How do I change the font size and color in an Excel Drop Down List?

Unfortunately, you can't change the font size or styling in a drop-down list that is created using data validation.

You can style the text in a combo box, however. Follow the instructions here: Excel Data Validation Combo Box

Insert variable into Header Location PHP

There's nothing here explaining the use of multiple variables, so I'll chuck it in just incase someone needs it in the future.

You need to concatenate multiple variables:

header('Location: http://linkhere.com?var1='.$var1.'&var2='.$var2.'&var3'.$var3);

"std::endl" vs "\n"

The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

How to replace substrings in windows batch file

If you have Ruby for Windows,

C:\>more file
bath Abath Bbath XYZbathABC

C:\>ruby -pne "$_.gsub!(/bath/,\"hello\")" file
hello Ahello Bhello XYZhelloABC

Detect Windows version in .net

These all seem like very complicated answers for a very simple function:

public bool IsWindows7 
{ 
    get 
    { 
        return (Environment.OSVersion.Version.Major == 6 &
            Environment.OSVersion.Version.Minor == 1); 
    } 
}

C++ undefined reference to defined function

As Paul said, this can be a linker complaint, rather than a compiler error. If you read your build output/logs carefully (may need to look in a separate IDE window to see the full details) you can dell if the problem is from the compiler (needs to be fixed in code) or from the linker (and need to be fixed in the make/cmake/project level to include a missing lib).

Check if key exists in JSON object using jQuery

if you have an array

var subcategories=[{name:"test",desc:"test"}];

function hasCategory(nameStr) {
        for(let i=0;i<subcategories.length;i++){
            if(subcategories[i].name===nameStr){
                return true;
            }
        }
        return false;
    }

if you have an object

var category={name:"asd",test:""};

if(category.hasOwnProperty('name')){//or category.name!==undefined
   return true;
}else{
   return false;
}

Postgres FOR LOOP

I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.

import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
                                  , password="***"
                                  , port="5432"
                                  , database="myDB"
                                  , host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()

myList = [...]
for item in myList:
  cursor_psql.execute('''
    -- The query goes here
  ''')

connection_psql.commit()
cursor_psql.close()

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

Change text from "Submit" on input tag

<input name="submitBnt" type="submit" value="like"/>

name is useful when using $_POST in php and also in javascript as document.getElementByName('submitBnt'). Also you can use name as a CS selector like input[name="submitBnt"]; Hope this helps

How to delete duplicate rows in SQL Server?

DECLARE @TB TABLE(NAME VARCHAR(100));
INSERT INTO @TB VALUES ('Red'),('Red'),('Green'),('Blue'),('White'),('White')
--**Delete by Rank**
;WITH CTE AS(SELECT NAME,DENSE_RANK() OVER (PARTITION BY NAME ORDER BY NEWID()) ID FROM @TB)
DELETE FROM CTE WHERE ID>1
SELECT NAME FROM @TB;
--**Delete by Row Number** 
;WITH CTE AS(SELECT NAME,ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) ID FROM @TB)
DELETE FROM CTE WHERE ID>1;
SELECT NAME FROM @TB;

How to detect simple geometric shapes using OpenCV

If you have only these regular shapes, there is a simple procedure as follows :

  1. Find Contours in the image ( image should be binary as given in your question)
  2. Approximate each contour using approxPolyDP function.
  3. First, check number of elements in the approximated contours of all the shapes. It is to recognize the shape. For eg, square will have 4, pentagon will have 5. Circles will have more, i don't know, so we find it. ( I got 16 for circle and 9 for half-circle.)
  4. Now assign the color, run the code for your test image, check its number, fill it with corresponding colors.

Below is my example in Python:

import numpy as np
import cv2

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Below is the output:

enter image description here

Remember, it works only for regular shapes.

Alternatively to find circles, you can use houghcircles. You can find a tutorial here.

Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.

You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

Can't concat bytes to str

subprocess.check_output() returns bytes.

so you need to convert '\n' to bytes as well:

 f.write (plaintext + b'\n')

hope this helps

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

I prefer doing a "PAD" to the data. MySql calls it LPAD, but you can work your way around to doing the same thing in SQL Server.

ORDER BY  REPLACE(STR(ColName, 3), SPACE(1), '0') 

This formula will provide leading zeroes based on the Column's length of 3. This functionality is very useful in other situations outside of ORDER BY, so that is why I wanted to provide this option.

Results: 1 becomes 001, and 10 becomes 010, while 100 remains the same.

Change the row color in DataGridView based on the quantity of a cell value

Just remove the : in your Quantity. Make sure that your attribute is the same with the parameter you include in the code, like this:

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
        If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
            Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
        End If
    Next
End Sub

collapse cell in jupyter notebook

Create custom.js file inside ~/.jupyter/custom/ with following contents:

$("<style type='text/css'> .cell.code_cell.collapse { max-height:30px; overflow:hidden;} </style>").appendTo("head");
$('.prompt.input_prompt').on('click', function(event) {
    console.log("CLICKED", arguments)   
    var c = $(event.target.closest('.cell.code_cell'))
    if(c.hasClass('collapse')) {
        c.removeClass('collapse');
    } else {
        c.addClass('collapse');
    }
});

After saving, restart the server and refresh the notebook. You can collapse any cell by clicking on the input label (In[]).