Programs & Examples On #High load

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Multiple aggregate functions in HAVING clause

select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION   
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0

CSS3 transition on click using pure CSS

As jeremyjjbrow said, :active pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a> tag, and apply the :active on it, like this:

<a class="test">
    <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
 </a>

And the css:

.test:active .crossRotate {
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    }

Try it out... It works (at least on Chrome)!

Angular - How to apply [ngStyle] conditions

[ngStyle]="{'opacity': is_mail_sent ? '0.5' : '1' }"

How do I disable a Button in Flutter?

You can also use the AbsorbPointer, and you can use it in the following way:

AbsorbPointer(
      absorbing: true, // by default is true
      child: RaisedButton(
        onPressed: (){
          print('pending to implement onPressed function');
        },
        child: Text("Button Click!!!"),
      ),
    ),

If you want to know more about this widget, you can check the following link Flutter Docs

How to properly assert that an exception gets raised in pytest?

pytest.raises(Exception) is what you need.

Code

import pytest

def test_passes():
    with pytest.raises(Exception) as e_info:
        x = 1 / 0

def test_passes_without_info():
    with pytest.raises(Exception):
        x = 1 / 0

def test_fails():
    with pytest.raises(Exception) as e_info:
        x = 1 / 1

def test_fails_without_info():
    with pytest.raises(Exception):
        x = 1 / 1

# Don't do this. Assertions are caught as exceptions.
def test_passes_but_should_not():
    try:
        x = 1 / 1
        assert False
    except Exception:
        assert True

# Even if the appropriate exception is caught, it is bad style,
# because the test result is less informative
# than it would be with pytest.raises(e)
# (it just says pass or fail.)

def test_passes_but_bad_style():
    try:
        x = 1 / 0
        assert False
    except ZeroDivisionError:
        assert True

def test_fails_but_bad_style():
    try:
        x = 1 / 1
        assert False
    except ZeroDivisionError:
        assert True

Output

============================================================================================= test session starts ==============================================================================================
platform linux2 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4
collected 7 items 

test.py ..FF..F

=================================================================================================== FAILURES ===================================================================================================
__________________________________________________________________________________________________ test_fails __________________________________________________________________________________________________

    def test_fails():
        with pytest.raises(Exception) as e_info:
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:13: Failed
___________________________________________________________________________________________ test_fails_without_info ____________________________________________________________________________________________

    def test_fails_without_info():
        with pytest.raises(Exception):
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:17: Failed
___________________________________________________________________________________________ test_fails_but_bad_style ___________________________________________________________________________________________

    def test_fails_but_bad_style():
        try:
            x = 1 / 1
>           assert False
E           assert False

test.py:43: AssertionError
====================================================================================== 3 failed, 4 passed in 0.02 seconds ======================================================================================

Note that e_info saves the exception object so you can extract details from it. For example, if you want to check the exception call stack or another nested exception inside.

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

Create a symbolic link to OpenCV. Eg:

cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so
ln -s /usr/local/lib/python2.7/dist-packages/cv.py cv.py

How to clear all inputs, selects and also hidden fields in a form using jQuery?

I had a slightly more specialised case, a search form which had an input which had autocomplete for a person name. The Javascript code set a hidden input which from.reset() does not clear.

However I didn't want to reset all hidden inputs. There I added a class, search-value, to the hidden inputs which where to be cleared.

$('form#search-form').reset();
$('form#search-form input[type=hidden].search-value').val('');

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Android Layout Animations from bottom to top and top to bottom on ImageView click

I have solved my issue and now my animation works fine :) if anyone needed just copy my code and xml file and have a happy coding :)

My Activity MainActivity:

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

RelativeLayout rl_footer;
ImageView iv_header;
boolean isBottom = true;
Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rl_footer = (RelativeLayout) findViewById(R.id.rl_footer);
    iv_header = (ImageView) findViewById(R.id.iv_up_arrow);
    iv_header.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            iv_header.setImageResource(R.drawable.down_arrow);
            iv_header.setPadding(0, 10, 0, 0); 
            rl_footer.setBackgroundResource(R.drawable.up_manu_bar);
            if (isBottom) {
                SlideToAbove();
                isBottom = false;
            } else {
                iv_header.setImageResource(R.drawable.up_arrow);
                iv_header.setPadding(0, 0, 0, 10);
                rl_footer.setBackgroundResource(R.drawable.down_manu_bar1);
                SlideToDown();
                isBottom = true;
            }

        }
    });

}

public void SlideToAbove() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, -5.0f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            // lp.setMargins(0, 0, 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            rl_footer.setLayoutParams(lp);

        }

    });

}

public void SlideToDown() {
    Animation slide = null;
    slide = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 5.2f);

    slide.setDuration(400);
    slide.setFillAfter(true);
    slide.setFillEnabled(true);
    rl_footer.startAnimation(slide);

    slide.setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {

            rl_footer.clearAnimation();

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    rl_footer.getWidth(), rl_footer.getHeight());
            lp.setMargins(0, rl_footer.getWidth(), 0, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            rl_footer.setLayoutParams(lp);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

and my Xml activity_main:

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rl_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@drawable/autograph_bg" >

 <RelativeLayout
    android:id="@+id/rl_footer"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    android:background="@drawable/down_manu_bar1" >

    <ImageView
        android:id="@+id/iv_new_file"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="18dp"
        android:onClick="onNewFileClick"
        android:src="@drawable/file_icon" />

    <TextView
        android:id="@+id/tv_new_file"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_new_file"
        android:layout_below="@+id/iv_new_file"
        android:text="New"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_insert"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_new_file"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_new_file"
        android:src="@drawable/insert_icon" />

    <TextView
        android:id="@+id/tv_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_insert"
        android:layout_below="@+id/iv_insert"
        android:text="Insert"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_up_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:paddingBottom="10dp"
        android:src="@drawable/up_arrow" />

    <ImageView
        android:id="@+id/iv_down_arrow"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/down_arrow"
        android:paddingBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/iv_save"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_insert"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/iv_up_arrow"
        android:src="@drawable/save" />

    <TextView
        android:id="@+id/tv_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/iv_save"
        android:layout_alignParentBottom="true"
        android:text="Save"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/iv_settings"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignTop="@+id/iv_save"
        android:layout_marginLeft="27dp"
        android:layout_toRightOf="@+id/tv_save"
        android:paddingTop="2dp"
        android:src="@drawable/icon_settings" />

    <TextView
        android:id="@+id/tv_settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="260dp"
        android:text="Settings"
        android:textColor="#ffffff" />
 </RelativeLayout>

 </RelativeLayout>

just create new android project and copy paste my code and have fun! :) also remember in xml i have image view and his background images replace with yout own images thanks..

Inconsistent Accessibility: Parameter type is less accessible than method

Constructor of public class clients is public but it has a parameter of type ACTInterface that is private (it is nested in a class?). You can't do that. You need to make ACTInterface at least as accessible as clients.

How do I resolve "Run-time error '429': ActiveX component can't create object"?

This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.

http://www.microsoft.com/en-ca/download/details.aspx?id=13255

QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"

Saving an image in OpenCV

In my experience OpenCV writes a black image when SaveImage is given a matrix with bit depth different from 8 bit. In fact, this is sort of documented:

Only 8-bit single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use cvCvtScale and cvCvtColor to convert it before saving, or use universal cvSave to save the image to XML or YAML format.

In your case you may first investigate what kind of image is captured, change capture properties (I suppose CV_CAP_PROP_CONVERT_RGB might be important) or convert it manually afterwards.

This is an example how to convert to 8-bit representation with OpenCV. cc here is an original matrix of type CV_32FC1, cc8u is its scaled version which is actually written by SaveImage:

# I want to save cc here
cc8u = CreateMat(cc.rows, cc.cols, CV_8U)
ccmin,ccmax,minij,maxij = MinMaxLoc(cc)
ccscale, ccshift = 255.0/(ccmax-ccmin), -ccmin
CvtScale(cc, cc8u, ccscale, ccshift)
SaveImage("cc.png", cc8u)

(sorry, this is Python code, but it should be easy to translate it to C/C++)

HTTP Status 404 - The requested resource (/) is not available

Sometimes cleaning the server works. It worked for me many times.This is only applicable if the program worked earlier but suddenly it stops working.
Steps:
" Right click on Tomcat Server -> Clean. Then restart the server."

Difference between Static methods and Instance methods

Difference between Static methods and Instance methods

  1. Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.

  2. Static method is declared with static keyword. Instance method is not with static keyword.

  3. Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.

  4. Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.

  5. Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.

Reference : geeksforgeeks

How to detect if multiple keys are pressed at once using JavaScript?

for who needs complete example code. Right+Left added

var keyPressed = {};
document.addEventListener('keydown', function(e) {

   keyPressed[e.key + e.location] = true;

    if(keyPressed.Shift1 == true && keyPressed.Control1 == true){
        // Left shift+CONTROL pressed!
        keyPressed = {}; // reset key map
    }
    if(keyPressed.Shift2 == true && keyPressed.Control2 == true){
        // Right shift+CONTROL pressed!
        keyPressed = {};
    }

}, false);

document.addEventListener('keyup', function(e) {
   keyPressed[e.key + e.location] = false;

   keyPressed = {};
}, false);

How to find GCD, LCM on a set of numbers

int gcf(int a, int b)
{
    while (a != b) // while the two numbers are not equal...
    { 
        // ...subtract the smaller one from the larger one

        if (a > b) a -= b; // if a is larger than b, subtract b from a
        else b -= a; // if b is larger than a, subtract a from b
    }

    return a; // or return b, a will be equal to b either way
}

int lcm(int a, int b)
{
    // the lcm is simply (a * b) divided by the gcf of the two

    return (a * b) / gcf(a, b);
}

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Assuming those methods are in one of the libs it looks like an ordering problem.

When linking libraries into an executable they are done in the order they are declared.
Also the linker will only take the methods/functions required to resolve currently outstanding dependencies. If a subsequent library then uses methods/functions that were not originally required by the objects you will have missing dependencies.

How it works:

  • Take all the object files and combine them into an executable
  • Resolve any dependencies among object files.
  • For-each library in order:
    • Check unresolved dependencies and see if the lib resolves them.
    • If so load required part into the executable.

Example:

Objects requires:

  • Open
  • Close
  • BatchRead
  • BatchWrite

Lib 1 provides:

  • Open
  • Close
  • read
  • write

Lib 2 provides

  • BatchRead (but uses lib1:read)
  • BatchWrite (but uses lib1:write)

If linked like this:

gcc -o plop plop.o -l1 -l2

Then the linker will fail to resolve the read and write symbols.

But if I link the application like this:

gcc -o plop plop.o -l2 -l1

Then it will link correctly. As l2 resolves the BatchRead and BatchWrite dependencies but also adds two new ones (read and write). When we link with l1 next all four dependencies are resolved.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

I had same problem with an Apple Sample Code. In project "PhotoPicker", in Architectures, the base SDK was:

screen shot 1

This parametrization provokes the message:

CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 7.1'

It assumes you have a developer user, so... use it and change:

screen shot 2

And the error disappears.

node.js execute system command synchronously

Node.js (since version 0.12 - so for a while) supports execSync:

child_process.execSync(command[, options])

You can now directly do this:

const execSync = require('child_process').execSync;
code = execSync('node -v');

and it'll do what you expect. (Defaults to pipe the i/o results to the parent process). Note that you can also spawnSync now.

Does it make sense to use Require.js with Angular.js?

Answer from Brian Ford

AngularJS has it's own module system an typically doesn't need something like RJS.

Reference: https://github.com/yeoman/generator-angular/issues/40

When to use "new" and when not to, in C++?

New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;

anaconda update all possible packages?

if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

This error occurred to me while trying to connect to the Google Cloud SQL using MySQL Workbench 6.3.

After a little research I found that my IP address has been changed by the internet provider and he was not allowed in the Cloud SQL.

I authorized it and went back to work.

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
   "nd"
else
    totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')

The above logic should be what you are looking for.

Lock screen orientation (Android)

inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,

android:screenOrientation="landscape"

for landscape orientation and for portrait add the following code,

android:screenOrientation="portrait"

Change Image of ImageView programmatically in Android

You can use

val drawableCompat = ContextCompat.getDrawable(context, R.drawable.ic_emoticon_happy)

or in java java

Drawable drawableCompat = ContextCompat.getDrawable(getContext(), R.drawable.ic_emoticon_happy)

Run javascript script (.js file) in mongodb including another file inside js

Use Load function

load(filename)

You can directly call any .js file from the mongo shell, and mongo will execute the JavaScript.

Example : mongo localhost:27017/mydb myfile.js

This executes the myfile.js script in mongo shell connecting to mydb database with port 27017 in localhost.

For loading external js you can write

load("/data/db/scripts/myloadjs.js")

Suppose we have two js file myFileOne.js and myFileTwo.js

myFileOne.js

print('From file 1');
load('myFileTwo.js');     // Load other js file .

myFileTwo.js

print('From file 2');

MongoShell

>mongo myFileOne.js

Output

From file 1
From file 2

How can I initialize a MySQL database with schema in a Docker container?

I've tried Greg's answer with zero success, I must have done something wrong since my database had no data after all the steps: I was using MariaDB's latest image, just in case.

Then I decided to read the entrypoint for the official MariaDB image, and used that to generate a simple docker-compose file:

database:
  image: mariadb
  ports:
     - 3306:3306
  expose:
     - 3306
  volumes:
     - ./docker/mariadb/data:/var/lib/mysql:rw
     - ./database/schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
  environment:
     MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

Now I'm able to persist my data AND generate a database with my own schema!

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

Decrementing for loops

You need to give the range a -1 step

 for i in range(10,0,-1):
    print i

Equivalent of Oracle's RowID in SQL Server

From the Oracle docs

ROWID Pseudocolumn

For each row in the database, the ROWID pseudocolumn returns the address of the row. Oracle Database rowid values contain information necessary to locate a row:

  • The data object number of the object
  • The data block in the datafile in which the row resides
  • The position of the row in the data block (first row is 0)
  • The datafile in which the row resides (first file is 1). The file number is relative to the tablespace.

The closest equivalent to this in SQL Server is the rid which has three components File:Page:Slot.

In SQL Server 2008 it is possible to use the undocumented and unsupported %%physloc%% virtual column to see this. This returns a binary(8) value with the Page ID in the first four bytes, then 2 bytes for File ID, followed by 2 bytes for the slot location on the page.

The scalar function sys.fn_PhysLocFormatter or the sys.fn_PhysLocCracker TVF can be used to convert this into a more readable form

CREATE TABLE T(X INT);

INSERT INTO T VALUES(1),(2)

SELECT %%physloc%% AS [%%physloc%%],
       sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot]
FROM T

Example Output

+--------------------+----------------+
|    %%physloc%%     | File:Page:Slot |
+--------------------+----------------+
| 0x2926020001000000 | (1:140841:0)   |
| 0x2926020001000100 | (1:140841:1)   |
+--------------------+----------------+

Note that this is not leveraged by the query processor. Whilst it is possible to use this in a WHERE clause

SELECT *
FROM T
WHERE %%physloc%% = 0x2926020001000100 

SQL Server will not directly seek to the specified row. Instead it will do a full table scan, evaluate %%physloc%% for each row and return the one that matches (if any do).

To reverse the process carried out by the 2 previously mentioned functions and get the binary(8) value corresponding to known File,Page,Slot values the below can be used.

DECLARE @FileId int = 1,
        @PageId int = 338,
        @Slot   int = 3

SELECT CAST(REVERSE(CAST(@PageId AS BINARY(4))) AS BINARY(4)) +
       CAST(REVERSE(CAST(@FileId AS BINARY(2))) AS BINARY(2)) +
       CAST(REVERSE(CAST(@Slot   AS BINARY(2))) AS BINARY(2))

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

Correct way to select from two tables in SQL Server with no common field to join on

A suggestion - when using cross join please take care of the duplicate scenarios. For example in your case:

  • Table 1 may have >1 columns as part of primary keys(say table1_id, id2, id3, table2_id)
  • Table 2 may have >1 columns as part of primary keys(say table2_id, id3, id4)

since there are common keys between these two tables (i.e. foreign keys in one/other) - we will end up with duplicate results. hence using the following form is good:

WITH data_mined_table (col1, col2, col3, etc....) AS
SELECT DISTINCT col1, col2, col3, blabla
FROM table_1 (NOLOCK), table_2(NOLOCK))
SELECT * from data_mined WHERE data_mined_table.col1 = :my_param_value

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

The exception clearly identifies some .NET 2.0.50727 component was included in .NET 4.0. In App.config file use this:

<startup useLegacyV2RuntimeActivationPolicy="true" /> 

It solved my problem

Changing datagridview cell color based on condition

Without looping it can be achived like below.

private void dgEvents_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {

        FormatRow(dgEvents.Rows[e.RowIndex]);

    }

private void FormatRow(DataGridViewRow myrow)
    {
        try
        {
            if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Error")
            {
                myrow.DefaultCellStyle.BackColor = Color.Red;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Warning")
            {
                myrow.DefaultCellStyle.BackColor = Color.Yellow;
            }
            else if (Convert.ToString(myrow.Cells["LevelDisplayName"].Value) == "Information")
            {
                myrow.DefaultCellStyle.BackColor = Color.LightGreen;
            }
        }
        catch (Exception exception)
        {
            onLogs?.Invoke(exception.Message, EventArgs.Empty);
        }
    }

Python Prime number checker

This would do the job:

number=int(raw_input("Enter a number to see if its prime:"))
if number <= 1:
    print "number is not prime"
else:
    a=2
    check = True
    while a != number:
        if number%a == 0:
            print "Number is not prime"
            check = False
            break
        a+=1
    if check == True:
        print "Number is prime" 

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

" This function preserves the list of jumps

fun! Dos2unixFunction()
let _s=@/
let l = line(".")
let c = col(".")
try
    set ff=unix
    w!
    "%s/\%x0d$//e
catch /E32:/
    echo "Sorry, the file is not saved."
endtry
let @/=_s
call cursor(l, c)
endfun
com! Dos2Unix keepjumps call Dos2unixFunction()

A regex for version number parsing

(?ms)^((?:\d+(?!\.\*)\.)+)(\d+)?(\.\*)?$|^(\d+)\.\*$|^(\*|\d+)$

Does exactly match your 6 first examples, and rejects the 4 others

  • group 1: major or major.minor or '*'
  • group 2 if exists: minor or *
  • group 3 if exists: *

You can remove '(?ms)'
I used it to indicate to this regexp to be applied on multi-lines through QuickRex

How to SELECT by MAX(date)?

It works great for me

SELECT report_id,computer_id,MAX(date_entered) FROM reports GROUP BY computer_id

Delete item from array and shrink array

Since an array has a fixed size that is allocated when created, your only option is to create a new array without the element you want to remove.

If the element you want to remove is the last array item, this becomes easy to implement using Arrays.copy:

int a[] = { 1, 2, 3};
a = Arrays.copyOf(a, 2);

After running the above code, a will now point to a new array containing only 1, 2.

Otherwise if the element you want to delete is not the last one, you need to create a new array at size-1 and copy all the items to it except the one you want to delete.

The approach above is not efficient. If you need to manage a mutable list of items in memory, better use a List. Specifically LinkedList will remove an item from the list in O(1) (fastest theoretically possible).

How to create UILabel programmatically using Swift?

Create UILabel view outside viewDidLoad class and then add that view to your main view in viewDidLoad method.

lazy var myLabel: UILabel = {


    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "This is label view."
    label.font = UIFont.systemFont(ofSize: 12)
    return label
}()

And then add that view in viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(myLabel)

    // Set its constraint to display it on screen
    myLabel.widthAnchor.constraint(equalToConstant:  200).isActive = true
    myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}

What are type hints in Python 3.5?

Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int) doesn't result in an error until the next return... line:

class C1:
    def __init__(self):
        self.idn = 1
    def add(self, ic: int):
        return self.idn + ic

c1 = C1()
c1.add(2)

c1.add(c1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'

How to get time difference in minutes in PHP

<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>

What is a 'NoneType' object?

NoneType is simply the type of the None singleton:

>>> type(None)
<type 'NoneType'>

From the latter link above:

None

The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.

In your case, it looks like one of the items you are trying to concatenate is None, hence your error.

how to use math.pi in java

Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it

Ex:

diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");

'Incomplete final line' warning when trying to read a .csv file into R

The problem is easy to resolve; it's because the last line MUST be empty.

Say, if your content is

line 1,
line2

change it to

line 1,
line2
(empty line here)

Today I met this kind problem, when I was trying to use R to read a JSON file, by using command below:

json_data<-fromJSON(paste(readLines("json01.json"), collapse=""))

; and I resolve it by my above method.

HTML.ActionLink method

what about this

<%=Html.ActionLink("Get Involved", 
                   "Show", 
                   "Home", 
                   new 
                       { 
                           id = "GetInvolved" 
                       }, 
                   new { 
                           @class = "menuitem", 
                           id = "menu_getinvolved" 
                       }
                   )%>

Converting Columns into rows with their respective data in sql server

select 'ScriptName', scriptName from table
union all
select 'ScriptCode', scriptCode from table
union all
select 'Price', price from table

Get the closest number out of an array

ES5 Version:

_x000D_
_x000D_
var counts = [4, 9, 15, 6, 2],_x000D_
  goal = 5;_x000D_
_x000D_
var closest = counts.reduce(function(prev, curr) {_x000D_
  return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);_x000D_
});_x000D_
_x000D_
console.log(closest);
_x000D_
_x000D_
_x000D_

Get generic type of class at runtime

To complete some of the answers here, I had to get the ParametrizedType of MyGenericClass, no matter how high is the hierarchy, with the help of recursion:

private Class<T> getGenericTypeClass() {
        return (Class<T>) (getParametrizedType(getClass())).getActualTypeArguments()[0];
}

private static ParameterizedType getParametrizedType(Class clazz){
    if(clazz.getSuperclass().equals(MyGenericClass.class)){ // check that we are at the top of the hierarchy
        return (ParameterizedType) clazz.getGenericSuperclass();
    } else {
        return getParametrizedType(clazz.getSuperclass());
    }
}

Linux - Install redis-cli only

To expand on @Agis's answer, you can also install the Redis CLI by running

$ git clone -b v2.8.7 [email protected]:antirez/redis.git
$ make -C redis install redis-cli /usr/bin

This will build the Redis CLI and toss the binary into /usr/bin. To anyone who uses Docker, I've also built a Dockerfile that does this for you: https://github.com/bacongobbler/dockerfiles/blob/master/redis-cli/Dockerfile

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

How to change active class while click to another link in bootstrap use jquery?

This will do the trick

 $(document).ready(function () {
        var url = window.location;
        var element = $('ul.nav a').filter(function() {
            return this.href == url || url.href.indexOf(this.href) == 0;
        }).addClass('active').parent().parent().addClass('in').parent();
        if (element.is('li')) {
            element.addClass('active');
        }
    });

How to animate CSS Translate

There's an interesting way which this can be achieved by using jQuery animate method in a unique way, where you call the animate method on a javascript Object which describes the from value and then you pass as the first parameter another js object which describes the to value, and a step function which handles each step of the animation according to the values described earlier.

Example - Animate transform translateY:

_x000D_
_x000D_
var $elm = $('h1'); // element to be moved_x000D_
_x000D_
function run( v ){_x000D_
  // clone the array (before "animate()" modifies it), and reverse it_x000D_
  var reversed = JSON.parse(JSON.stringify(v)).reverse();_x000D_
  _x000D_
  $(v[0]).animate(v[1], {_x000D_
      duration: 500,_x000D_
      step: function(val) {_x000D_
          $elm.css("transform", `translateY(${val}px)`); _x000D_
      },_x000D_
      done: function(){_x000D_
          run( reversed )_x000D_
      }_x000D_
  })_x000D_
};_x000D_
_x000D_
// "y" is arbitrary used as the key name _x000D_
run( [{y:0}, {y:80}] )
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>jQuery animate <pre>transform:translateY()</pre></h1>
_x000D_
_x000D_
_x000D_

jQuery: find element by text

The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.

_x000D_
_x000D_
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
_x000D_
<div>div1_x000D_
<div>This is a test, nested in div1</div>_x000D_
<div>Nested in div1<div>_x000D_
</div>_x000D_
<div>div2 test_x000D_
<div>This is another test, nested in div2</div>_x000D_
<div>Nested in div2</div>_x000D_
</div>_x000D_
<div>_x000D_
div3_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Regex not operator

Not quite, although generally you can usually use some workaround on one of the forms

  • [^abc], which is character by character not a or b or c,
  • or negative lookahead: a(?!b), which is a not followed by b
  • or negative lookbehind: (?<!a)b, which is b not preceeded by a

How to align 3 divs (left/center/right) inside another div?

With twitter bootstrap :

<p class="pull-left">Left aligned text.</p>
<p class="pull-right">Right aligned text.</p>
<p class="text-center">Center aligned text.</p>

Could not find main class HelloWorld

Java is not finding where your compiled class file (HelloWorld.class) is. It uses the directories and JAR-files in the CLASSPATH environment variable for searching if no -cp or -classpath option is given when running java.exe.

You don't need the rt.jar in the CLASSPATH, these was only needed for older versions of Java. You can leave it undefined and the current working directory will be used, or just add . (a single point), separated by ';', to the CLASSPATH variable to indicate the current directory:

CLASSPATH: .;C:\...\some.jar

Alternatively you can use the -cp or -classpath option:

java -cp . HelloWorld

And, as Andreas wrote, JAVA_HOME is not needed by Java, just for some third-party tools like ant (but should point to the correct location).

How to serve up images in Angular2?

Add your image path like fullPathname='assets/images/therealdealportfoliohero.jpg' in your constructor. It will work definitely.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

This was totally my bad.

I was using standard node http.request on a part of the code which should be sending requests to only http adresses. Seems like the db had a single https address which was queried with a random interval.

Simply, I was trying to send a http request to https.

javascript : sending custom parameters with window.open() but its not working

To concatenate strings, use the + operator.

To insert data into a URI, encode it for URIs.

Bad:

var url = "http://localhost:8080/login?cid='username'&pwd='password'"

Good:

var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;

The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.

… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).

How can I check if a JSON is empty in NodeJS?

If you have compatibility with Object.keys, and node does have compatibility, you should use that for sure.

However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:

JSON.stringify(obj) === '{}'

Consider this solution a 'last resort' use only if must.

See in the comments "there are many ways in which this solution is not ideal".

I had a last resort scenario, and it worked perfectly.

Float a div above page content

Use

position: absolute;
top: ...px;
left: ...px;

To position the div. Make sure it doesn't have a parent tag with position: relative;

Most concise way to convert a Set<T> to a List<T>

Try this for Set:

Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors); 

Try this for Map:

Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());

What does an exclamation mark mean in the Swift language?

If you're familiar with C#, this is like Nullable types which are also declared using a question mark:

Person? thisPerson;

And the exclamation mark in this case is equivalent to accessing the .Value property of the nullable type like this:

thisPerson.Value

jQuery add image inside of div tag

var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
                var imgsrc = jQuery('.MulImage')[i];
                var CurrentImgSrc = imgsrc.src;
                img = jQuery('<img class="dynamic" style="width:100%;">');
                img.attr('src', CurrentImgSrc);
                jQuery('.YourDivClass').append(img);

            }

What is the best IDE for C Development / Why use Emacs over an IDE?

Emacs is an IDE.

edit: OK, I'll elaborate. What is an IDE?

As a starting point, let's expand the acronym: Integrated Development Environment. To analyze this, I start from the end.

An environment is, generally speaking, the part of the world that surrounds the point of view. In this case, it is what we see on our monitor (perhaps hear from our speakers) and manipulate through our keyboard (and perhaps a mouse).

Development is what we want to do in this environment, its purpose, if you want. We use the environment to develop software. This defines what subparts we need: an editor, an interface to the REPL, resp. the compiler, an interface to the debugger, and access to online documentation (this list may not be exhaustive).

Integrated means that all parts of the environment are somehow under a uniform surface. In an IDE, we can access and use the different subparts with a minimum of switching; we don't have to leave our defined environment. This integration lets the different subparts interact better. For example, the editor can know about what language we write in, and give us symbol autocompletion, jump-to-definition, auto-indentation, syntax highlighting, etc.. It can get information from the compiler, automatically jump to errors, and highlight them. In most, if not all IDEs, the editor is naturally at the heart of the development process.

Emacs does all this, it does it with a wide range of languages and tasks, and it does it with excellence, since it is seamlessly expandable by the user wherever he misses anything.

Counterexample: you could develop using something like Notepad, access documentation through Firefox and XPdf, and steer the compiler and debugger from a shell. This would be a Development Environment, but it would not be integrated.

Asp.net - Add blank item at top of dropdownlist

Like "Whisk" Said, the trick is in "AppendDataBoundItems" property

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DropDownList1.AppendDataBoundItems = true;
        DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
        DropDownList1.SelectedIndex = 0;
    }
}

Thanks "Whisk"

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

How do you Change a Package's Log Level using Log4j?

This work for my:

log4j.logger.org.hibernate.type=trace

Also can try:

log4j.category.org.hibernate.type=trace

How can I query for null values in entity framework?

If you prefer using method (lambda) syntax as I do, you could do the same thing like this:

var result = new TableName();

using(var db = new EFObjectContext)
{
    var query = db.TableName;

    query = value1 == null 
        ? query.Where(tbl => tbl.entry1 == null) 
        : query.Where(tbl => tbl.entry1 == value1);

    query = value2 == null 
        ? query.Where(tbl => tbl.entry2 == null) 
        : query.Where(tbl => tbl.entry2 == value2);

    result = query
        .Select(tbl => tbl)
        .FirstOrDefault();

   // Inspect the value of the trace variable below to see the sql generated by EF
   var trace = ((ObjectQuery<REF_EQUIPMENT>) query).ToTraceString();

}

return result;

"Conversion to Dalvik format failed with error 1" on external JAR

I had the same error, and tried everything above but nothing helped me.

My projects are attached to GIT source control system, and I realized that there are some GIT related task while exporting to Andorid application. Then I commited all changes to the GIT repository and error dissapear.

So, if you are using GIT for source control and nothing above help you, try to commit all changes to the GIT repository (and eventually push to upstream) and try export again.

How to Resize image in Swift?

Details

  • Xcode 10.2.1 (10E1001), Swift 5

Links

Solution

import UIKit
import CoreGraphics
import Accelerate

extension UIImage {

    public enum ResizeFramework {
        case uikit, coreImage, coreGraphics, imageIO, accelerate
    }

    /// Resize image with ScaleAspectFit mode and given size.
    ///
    /// - Parameter dimension: width or length of the image output.
    /// - Parameter resizeFramework: Technique for image resizing: UIKit / CoreImage / CoreGraphics / ImageIO / Accelerate.
    /// - Returns: Resized image.

    func resizeWithScaleAspectFitMode(to dimension: CGFloat, resizeFramework: ResizeFramework = .coreGraphics) -> UIImage? {

        if max(size.width, size.height) <= dimension { return self }

        var newSize: CGSize!
        let aspectRatio = size.width/size.height

        if aspectRatio > 1 {
            // Landscape image
            newSize = CGSize(width: dimension, height: dimension / aspectRatio)
        } else {
            // Portrait image
            newSize = CGSize(width: dimension * aspectRatio, height: dimension)
        }

        return resize(to: newSize, with: resizeFramework)
    }

    /// Resize image from given size.
    ///
    /// - Parameter newSize: Size of the image output.
    /// - Parameter resizeFramework: Technique for image resizing: UIKit / CoreImage / CoreGraphics / ImageIO / Accelerate.
    /// - Returns: Resized image.
    public func resize(to newSize: CGSize, with resizeFramework: ResizeFramework = .coreGraphics) -> UIImage? {
        switch resizeFramework {
            case .uikit: return resizeWithUIKit(to: newSize)
            case .coreGraphics: return resizeWithCoreGraphics(to: newSize)
            case .coreImage: return resizeWithCoreImage(to: newSize)
            case .imageIO: return resizeWithImageIO(to: newSize)
            case .accelerate: return resizeWithAccelerate(to: newSize)
        }
    }

    // MARK: - UIKit

    /// Resize image from given size.
    ///
    /// - Parameter newSize: Size of the image output.
    /// - Returns: Resized image.
    private func resizeWithUIKit(to newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(newSize, true, 1.0)
        self.draw(in: CGRect(origin: .zero, size: newSize))
        defer { UIGraphicsEndImageContext() }
        return UIGraphicsGetImageFromCurrentImageContext()
    }

    // MARK: - CoreImage

    /// Resize CI image from given size.
    ///
    /// - Parameter newSize: Size of the image output.
    /// - Returns: Resized image.
    // https://developer.apple.com/library/archive/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html
    private func resizeWithCoreImage(to newSize: CGSize) -> UIImage? {
        guard let cgImage = cgImage, let filter = CIFilter(name: "CILanczosScaleTransform") else { return nil }

        let ciImage = CIImage(cgImage: cgImage)
        let scale = (Double)(newSize.width) / (Double)(ciImage.extent.size.width)

        filter.setValue(ciImage, forKey: kCIInputImageKey)
        filter.setValue(NSNumber(value:scale), forKey: kCIInputScaleKey)
        filter.setValue(1.0, forKey: kCIInputAspectRatioKey)
        guard let outputImage = filter.value(forKey: kCIOutputImageKey) as? CIImage else { return nil }
        let context = CIContext(options: [.useSoftwareRenderer: false])
        guard let resultCGImage = context.createCGImage(outputImage, from: outputImage.extent) else { return nil }
        return UIImage(cgImage: resultCGImage)
    }

    // MARK: - CoreGraphics

    /// Resize image from given size.
    ///
    /// - Parameter newSize: Size of the image output.
    /// - Returns: Resized image.
    private func resizeWithCoreGraphics(to newSize: CGSize) -> UIImage? {
        guard let cgImage = cgImage, let colorSpace = cgImage.colorSpace else { return nil }

        let width = Int(newSize.width)
        let height = Int(newSize.height)
        let bitsPerComponent = cgImage.bitsPerComponent
        let bytesPerRow = cgImage.bytesPerRow
        let bitmapInfo = cgImage.bitmapInfo

        guard let context = CGContext(data: nil, width: width, height: height,
                                      bitsPerComponent: bitsPerComponent,
                                      bytesPerRow: bytesPerRow, space: colorSpace,
                                      bitmapInfo: bitmapInfo.rawValue) else { return nil }
        context.interpolationQuality = .high
        let rect = CGRect(origin: CGPoint.zero, size: newSize)
        context.draw(cgImage, in: rect)

        return context.makeImage().flatMap { UIImage(cgImage: $0) }
    }

    // MARK: - ImageIO

    /// Resize image from given size.
    ///
    /// - Parameter newSize: Size of the image output.
    /// - Returns: Resized image.
    private func resizeWithImageIO(to newSize: CGSize) -> UIImage? {
        var resultImage = self

        guard let data = jpegData(compressionQuality: 1.0) else { return resultImage }
        let imageCFData = NSData(data: data) as CFData
        let options = [
            kCGImageSourceCreateThumbnailWithTransform: true,
            kCGImageSourceCreateThumbnailFromImageAlways: true,
            kCGImageSourceThumbnailMaxPixelSize: max(newSize.width, newSize.height)
            ] as CFDictionary
        guard   let source = CGImageSourceCreateWithData(imageCFData, nil),
                let imageReference = CGImageSourceCreateThumbnailAtIndex(source, 0, options) else { return resultImage }
        resultImage = UIImage(cgImage: imageReference)

        return resultImage
    }

    // MARK: - Accelerate

    /// Resize image from given size.
    ///
    /// - Parameter newSize: Size of the image output.
    /// - Returns: Resized image.
    private func resizeWithAccelerate(to newSize: CGSize) -> UIImage? {
        var resultImage = self

        guard let cgImage = cgImage, let colorSpace = cgImage.colorSpace else { return nil }

        // create a source buffer
        var format = vImage_CGImageFormat(bitsPerComponent: numericCast(cgImage.bitsPerComponent),
                                          bitsPerPixel: numericCast(cgImage.bitsPerPixel),
                                          colorSpace: Unmanaged.passUnretained(colorSpace),
                                          bitmapInfo: cgImage.bitmapInfo,
                                          version: 0,
                                          decode: nil,
                                          renderingIntent: .absoluteColorimetric)
        var sourceBuffer = vImage_Buffer()
        defer {
            sourceBuffer.data.deallocate()
        }

        var error = vImageBuffer_InitWithCGImage(&sourceBuffer, &format, nil, cgImage, numericCast(kvImageNoFlags))
        guard error == kvImageNoError else { return resultImage }

        // create a destination buffer
        let destWidth = Int(newSize.width)
        let destHeight = Int(newSize.height)
        let bytesPerPixel = cgImage.bitsPerPixel
        let destBytesPerRow = destWidth * bytesPerPixel
        let destData = UnsafeMutablePointer<UInt8>.allocate(capacity: destHeight * destBytesPerRow)
        defer {
            destData.deallocate()
        }
        var destBuffer = vImage_Buffer(data: destData, height: vImagePixelCount(destHeight), width: vImagePixelCount(destWidth), rowBytes: destBytesPerRow)

        // scale the image
        error = vImageScale_ARGB8888(&sourceBuffer, &destBuffer, nil, numericCast(kvImageHighQualityResampling))
        guard error == kvImageNoError else { return resultImage }

        // create a CGImage from vImage_Buffer
        let destCGImage = vImageCreateCGImageFromBuffer(&destBuffer, &format, nil, nil, numericCast(kvImageNoFlags), &error)?.takeRetainedValue()
        guard error == kvImageNoError else { return resultImage }

        // create a UIImage
        if let scaledImage = destCGImage.flatMap({ UIImage(cgImage: $0) }) {
            resultImage = scaledImage
        }

        return resultImage
    }
}

Usage

Get image size

import UIKit

// https://stackoverflow.com/a/55765409/4488252
extension UIImage {
    func getFileSizeInfo(allowedUnits: ByteCountFormatter.Units = .useMB,
                         countStyle: ByteCountFormatter.CountStyle = .memory,
                         compressionQuality: CGFloat = 1.0) -> String? {
        // https://developer.apple.com/documentation/foundation/bytecountformatter
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = allowedUnits
        formatter.countStyle = countStyle
        return getSizeInfo(formatter: formatter, compressionQuality: compressionQuality)
    }

    func getSizeInfo(formatter: ByteCountFormatter, compressionQuality: CGFloat = 1.0) -> String? {
        guard let imageData = jpegData(compressionQuality: compressionQuality) else { return nil }
        return formatter.string(fromByteCount: Int64(imageData.count))
    }
}

Test function

private func test() {
    guard let img = UIImage(named: "img") else { return }
    printInfo(of: img, title: "original image |")
    let dimension: CGFloat = 2000

    var framework: UIImage.ResizeFramework = .accelerate
    var startTime = Date()
    if let img = img.resizeWithScaleAspectFitMode(to: dimension, resizeFramework: framework) {
        printInfo(of: img, title: "resized image |", with: framework, startedTime: startTime)
    }

    framework = .coreGraphics
    startTime = Date()
    if let img = img.resizeWithScaleAspectFitMode(to: dimension, resizeFramework: framework) {
        printInfo(of: img, title: "resized image |", with: framework, startedTime: startTime)
    }

    framework = .coreImage
    startTime = Date()
    if let img = img.resizeWithScaleAspectFitMode(to: dimension, resizeFramework: framework) {
        printInfo(of: img, title: "resized image |", with: framework, startedTime: startTime)
    }

    framework = .imageIO
    startTime = Date()
    if let img = img.resizeWithScaleAspectFitMode(to: dimension, resizeFramework: framework) {
        printInfo(of: img, title: "resized image |", with: framework, startedTime: startTime)
    }

    framework = .uikit
    startTime = Date()
    if let img = img.resizeWithScaleAspectFitMode(to: dimension, resizeFramework: framework) {
        printInfo(of: img, title: "resized image |", with: framework, startedTime: startTime)
    }
}

private func printInfo(of image: UIImage, title: String, with resizeFramework: UIImage.ResizeFramework? = nil, startedTime: Date? = nil) {
    var description = "\(title) \(image.size)"
    if let startedTime = startedTime { description += ", execution time: \(Date().timeIntervalSince(startedTime))" }
    if let fileSize = image.getFileSizeInfo(compressionQuality: 0.9) { description += ", size: \(fileSize)" }
    if let resizeFramework = resizeFramework { description += ", framework: \(resizeFramework)" }
    print(description)
}

Output

original image | (5790.0, 8687.0), size: 17.1 MB
resized image | (1333.0, 2000.0), execution time: 0.8192930221557617, size: 1.1 MB, framework: accelerate
resized image | (1333.0, 2000.0), execution time: 0.44696998596191406, size: 1 MB, framework: coreGraphics
resized image | (1334.0, 2000.0), execution time: 54.172922015190125, size: 1.1 MB, framework: coreImage
resized image | (1333.0, 2000.0), execution time: 1.8765920400619507, size: 1.1 MB, framework: imageIO
resized image | (1334.0, 2000.0), execution time: 0.4638739824295044, size: 1 MB, framework: uikit

How to get data out of a Node.js http get request

This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback

function getData(callbackData){
  var http = require('http');
  var str = '';

  var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
  };

  callback = function(response) {

        response.on('data', function (chunk) {
              str += chunk;
        });

        response.on('end', function () {
              console.log(str);
          callbackData(str);
        });

        //return str;
  }

  var req = http.request(options, callback).end();

  // These just return undefined and empty
  console.log(req.data);
  console.log(str);
}

somewhere else

getData(function(data){
// YOUR CODE HERE!!!
})

How do I force "git pull" to overwrite local files?

Warning, doing this will permanently delete your files if you have any directory/* entries in your gitignore file.

Some answers seem to be terrible. Terrible in the sense of what happened to @Lauri by following David Avsajanishvili suggestion.

Rather (git > v1.7.6):

git stash --include-untracked
git pull

Later you can clean the stash history.

Manually, one-by-one:

$ git stash list
stash@{0}: WIP on <branch>: ...
stash@{1}: WIP on <branch>: ...

$ git stash drop stash@{0}
$ git stash drop stash@{1}

Brutally, all-at-once:

$ git stash clear

Of course if you want to go back to what you stashed:

$ git stash list
...
$ git stash apply stash@{5}

How to assign name for a screen?

As already stated, screen -S SESSIONTITLE works for starting a session with a title (SESSIONTITLE), but if you start a session and later decide to change its title. This can be accomplished by using the default key bindings:

Ctrl+a, A

Which prompts:

Set windows title to:SESSIONTITLE

Change SESSIONTITLE by backspacing and typing in the desired title. To confirm the name change and list all titles.

Ctrl+a, "

CFNetwork SSLHandshake failed iOS 9

After two days of attempts and failures, what worked for me is this code of womble

with One change, according to this post we should stop using sub-keys associated with the NSExceptionDomains dictionary of that kind of Convention

  NSTemporaryExceptionMinimumTLSVersion

And use at the new Convention

  NSExceptionMinimumTLSVersion

instead.

apple documentation

my code

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>YOUR_HOST.COM</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionMinimumTLSVersion</key>
                <string>TLSv1.0</string>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
        </dict>
    </dict>

Android camera android.hardware.Camera deprecated

Faced with the same issue, supporting older devices via the deprecated camera API and needing the new Camera2 API for both current devices and moving into the future; I ran into the same issues -- and have not found a 3rd party library that bridges the 2 APIs, likely because they are very different, I turned to basic OOP principals.

The 2 APIs are markedly different making interchanging them problematic for client objects expecting the interfaces presented in the old API. The new API has different objects with different methods, built using a different architecture. Got love for Google, but ragnabbit! that's frustrating.

So I created an interface focussing on only the camera functionality my app needs, and created a simple wrapper for both APIs that implements that interface. That way my camera activity doesn't have to care about which platform its running on...

I also set up a Singleton to manage the API(s); instancing the older API's wrapper with my interface for older Android OS devices, and the new API's wrapper class for newer devices using the new API. The singleton has typical code to get the API level and then instances the correct object.

The same interface is used by both wrapper classes, so it doesn't matter if the App runs on Jellybean or Marshmallow--as long as the interface provides my app with what it needs from either Camera API, using the same method signatures; the camera runs in the App the same way for both newer and older versions of Android.

The Singleton can also do some related things not tied to the APIs--like detecting that there is indeed a camera on the device, and saving to the media library.

I hope the idea helps you out.

Sort a Map<Key, Value> by values

Instead of using Collections.sort as some do I'd suggest using Arrays.sort. Actually what Collections.sort does is something like this:

public static <T extends Comparable<? super T>> void sort(List<T> list) {
    Object[] a = list.toArray();
    Arrays.sort(a);
    ListIterator<T> i = list.listIterator();
    for (int j=0; j<a.length; j++) {
        i.next();
        i.set((T)a[j]);
    }
}

It just calls toArray on the list and then uses Arrays.sort. This way all the map entries will be copied three times: once from the map to the temporary list (be it a LinkedList or ArrayList), then to the temporary array and finally to the new map.

My solution ommits this one step as it does not create unnecessary LinkedList. Here is the code, generic-friendly and performance-optimal:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) 
{
    @SuppressWarnings("unchecked")
    Map.Entry<K,V>[] array = map.entrySet().toArray(new Map.Entry[map.size()]);

    Arrays.sort(array, new Comparator<Map.Entry<K, V>>() 
    {
        public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) 
        {
            return e1.getValue().compareTo(e2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : array)
        result.put(entry.getKey(), entry.getValue());

    return result;
}

Odd behavior when Java converts int to byte?

here is a very mechanical method without the distracting theories:

  1. Convert the number into binary representation (use a calculator ok?)
  2. Only copy the rightmost 8 bits (LSB) and discard the rest.
  3. From the result of step#2, if the leftmost bit is 0, then use a calculator to convert the number to decimal. This is your answer.
  4. Else (if the leftmost bit is 1) your answer is negative. Leave all rightmost zeros and the first non-zero bit unchanged. And reversed the rest, that is, replace 1's by 0's and 0's by 1's. Then use a calculator to convert to decimal and append a negative sign to indicate the value is negative.

This more practical method is in accordance to the much theoretical answers above. So, those still reading those Java books saying to use modulo, this is definitely wrong since the 4 steps I outlined above is definitely not a modulo operation.

How to show image using ImageView in Android

Drag image from your hard drive to Drawable folder in your project and in code use it like this:

ImageView image;

image = (ImageView) findViewById(R.id.yourimageviewid);
image.setImageResource(R.drawable.imagename);

How to write log to file

Building on Allison and Deepak's answer, I started using logrus and really like it:

var log = logrus.New()

func init() {

    // log to console and file
    f, err := os.OpenFile("crawler.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("error opening file: %v", err)
    }
    wrt := io.MultiWriter(os.Stdout, f)

    log.SetOutput(wrt)
}

I have a defer f.Close() in the main function

Can promises have multiple arguments to onFulfilled?

De-structuring Assignment in ES6 would help here.For Ex:

let [arg1, arg2] = new Promise((resolve, reject) => {
    resolve([argument1, argument2]);
});

Replace tabs with spaces in vim

expand is a unix utility to convert tabs to spaces. If you do not want to set anything in vim, you can use a shell command from vim:

:!% expand -t8

jQuery check if <input> exists and has a value

I would do something like this: $('input[value]').something . This finds all inputs that have value and operates something onto them.

How to POST a FORM from HTML to ASPX page

Are you sure your HTML form is correct, and does, in fact, do an HTTP POST? I would suggest running Fiddler2, and then trying to log in via your Login.aspx, then the remote HTML site, and then comparing the requests that are sent to the server. For me, ASP.Net always worked fine -- if HTTP request contains a valid POST, I can get to values using Request.Form...

Sorting a vector of custom objects

A simple example using std::sort

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

struct less_than_key
{
    inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
    {
        return (struct1.key < struct2.key);
    }
};

std::vector < MyStruct > vec;

vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));

std::sort(vec.begin(), vec.end(), less_than_key());

Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the operator< for MyStruct:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator < (const MyStruct& str) const
    {
        return (key < str.key);
    }
};

Using this method means you can simply sort the vector as follows:

std::sort(vec.begin(), vec.end());

Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a > operator and changing call of sort a bit:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator > (const MyStruct& str) const
    {
        return (key > str.key);
    }
};

And you should call sort as:

std::sort(vec.begin(), vec.end(),greater<MyStruct>());

python pandas dataframe to dictionary

def get_dict_from_pd(df, key_col, row_col):
    result = dict()
    for i in set(df[key_col].values):
        is_i = df[key_col] == i
        result[i] = list(df[is_i][row_col].values)
    return result

this is my sloution, a basic loop

Async/Await Class Constructor

If you can avoid extend, you can avoid classes all together and use function composition as constructors. You can use the variables in the scope instead of class members:

async function buildA(...) {
  const data = await fetch(...);
  return {
    getData: function() {
      return data;
    }
  }
}

and simple use it as

const a = await buildA(...);

If you're using typescript or flow, you can even enforce the interface of the constructors

Interface A {
  getData: object;
}

async function buildA0(...): Promise<A> { ... }
async function buildA1(...): Promise<A> { ... }
...

search in java ArrayList

In Java 8:

Customer findCustomerByid(int id) {
    return this.customers.stream()
        .filter(customer -> customer.getId().equals(id))
        .findFirst().get();
}

It might also be better to change the return type to Optional<Customer>.

.Net picking wrong referenced assembly version

Its almost like you have to wipe out your computer to get rid of the old dll. I have already tried everything above and then I went the extra step of just deleting every instance of the .DLL file that was on my computer and removing every reference from the application. However, it still compiles just fine and when it runs it is referencing the dll functions just fine. I'm starting to wonder if it is referencing it from a network drive somehwere.

How do I format currencies in a Vue component?

The comment by @RoyJ has a great suggestion. In the template you can just use built-in localized strings:

<small>
     Total: <b>{{ item.total.toLocaleString() }}</b>
</small>

It's not supported in some of the older browsers, but if you're targeting IE 11 and later, you should be fine.

Visual Studio 2015 installer hangs during install?

The old thread with many answers. but for me, these commands solved the problem.

regsvr32.exe /u "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"

regsvr32.exe "C:\Program Files (x86)\Common Files\microsoft shared\MSI Tools\mergemod.dll"

Remove credentials from Git

git config --list

will show credential.helper = manager (this is on a windows machine)

To disable this cached username/password for your current local git folder, simply enter

git config credential.helper ""

This way, git will prompt for password every time, ignoring what's saved inside "manager".

How to make grep only match if the entire line matches?

Most suggestions will fail if there so much as a single leading or trailing space, which would matter if the file is being edited by hand. This would make it less susceptible in that case:

grep '^[[:blank:]]*ABB\.log[[:blank:]]*$' a.tmp

A simple while-read loop in shell would do this implicitly:

while read file
do 
  case $file in
    (ABB.log) printf "%s\n" "$file"
  esac
done < a.tmp

Java: Get first item from a collection

In java 8:

Optional<String> firstElement = collection.stream().findFirst();

For older versions of java, there is a getFirst method in Guava Iterables:

Iterables.getFirst(iterable, defaultValue)

Appending a list or series to a pandas DataFrame as a row?

Converting the list to a data frame within the append function works, also when applied in a loop

import pandas as pd
mylist = [1,2,3]
df = pd.DataFrame()
df = df.append(pd.DataFrame(data[mylist]))

How to manipulate arrays. Find the average. Beginner Java

Couple of problems:

The while should be a for You are not returning a value but you have declared a return type of double

double average = sum / data.length;;

sum and data.length are both ints so the division will return an int - check your types

double semi-colon, probably won't break it, just looks odd.

Sorting a tab delimited file

I wanted a solution for Gnu sort on Windows, but none of the above solutions worked for me on the command line.

Using Lloyd's clue, the following batch file (.bat) worked for me.

Type the tab character within the double quotes.

C:\>cat foo.bat

sort -k3 -t"    " tabfile.txt

Convert an int to ASCII character

My way to do this job is:

char to int
char var;
cout<<(int)var-48;
    
int to char
int var;
cout<<(char)(var|48);

And I write these functions for conversions:

int char2int(char *szBroj){
    int counter=0;
    int results=0;
    while(1){
        if(szBroj[counter]=='\0'){
            break;
        }else{
            results*=10;
            results+=(int)szBroj[counter]-48;
            counter++;
        }
    }
    return results;
}

char * int2char(int iNumber){
    int iNumbersCount=0;
    int iTmpNum=iNumber;
    while(iTmpNum){
        iTmpNum/=10;
        iNumbersCount++;
    }
    char *buffer=new char[iNumbersCount+1];
    for(int i=iNumbersCount-1;i>=0;i--){
        buffer[i]=(char)((iNumber%10)|48);
        iNumber/=10;
    }
    buffer[iNumbersCount]='\0';
    return buffer;
}

How to get user's high resolution profile picture on Twitter?

for me the "workaround" solution was to remove the "_normal" from the end of the string

Check it out below:

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

X-UA-Compatible will only override the Document Mode, not the Browser Mode, and will not work for all intranet sites; if this is your case, the best solution is to disable "Display intranet sites in Compatibility View" and set a group policy setting to specify which intranet sites need compatibility mode.

Unit tests vs Functional tests

Unit Test:- Unit testing is particularly used to test the product component by component specially while the product is under development. Junit and Nunit type of tools will also help you to test the product as per the Unit. **Rather than solving the issues after the Integration it is always comfortable to get it resolved early in the development.

Functional Testing:- As for as the Testing is concerned there are two main types of Testing as 1.Functional Test 2.Non-Functional Test.

Non-Functional Test is a test where a Tester will test that The product will perform all those quality attributes that customer doesn't mention but those quality attributes should be there. Like:-Performance,Usability,Security,Load,Stress etc. but in the Functional Test:- The customer is already present with his requirements and those are properly documented,The testers task is to Cross check that whether the Application Functionality is performing according to the Proposed System or not. For that purpose Tester should test for the Implemented functionality with the proposed System.

Compress files while reading data from STDIN

Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.

cat test.csv | gzip > test.csv.gz

cat test.csv will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.

Disable cache for some images

I was just looking for a solution to this, and the answers above didn't work in my case (and I have insufficient reputation to comment on them). It turns out that, at least for my use-case and the browser I was using (Chrome on OSX), the only thing that seemed to prevent caching was:

Cache-Control = 'no-store'

For completeness i'm now using all 3 of 'no-cache, no-store, must-revalidate'

So in my case (serving dynamically generated images out of Flask in Python), I had to do the following to hopefully work in as many browsers as possible...

def make_uncached_response(inFile):
    response = make_response(inFile)
    response.headers['Pragma-Directive'] = 'no-cache'
    response.headers['Cache-Directive'] = 'no-cache'
    response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '0'
    return response

How to access PHP session variables from jQuery function in a .js file?

If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.

So in page.php:

<script src="my_progress_bar.js"></script>
<script>
$(function () {
    var percent = <?php echo $_SESSION['percent']; ?>;
    $.my_progress_bar(percent);
});
</script>

Then in my_progress_bar.js:

(function ($) {
    $.my_progress_bar = function(percent) {
        $( "#progressbar" ).progressbar({
            value: percent
        });
    };
})(jQuery);

max value of integer

In C, the language itself does not determine the representation of certain datatypes. It can vary from machine to machine, on embedded systems the int can be 16 bit wide, though usually it is 32 bit.

The only requirement is that short int <= int <= long int by size. Also, there is a recommendation that int should represent the native capacity of the processor.

All types are signed. The unsigned modifier allows you to use the highest bit as part of the value (otherwise it is reserved for the sign bit).

Here's a short table of the possible values for the possible data types:

          width                     minimum                         maximum
signed    8 bit                        -128                            +127
signed   16 bit                     -32 768                         +32 767
signed   32 bit              -2 147 483 648                  +2 147 483 647
signed   64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807
unsigned  8 bit                           0                            +255
unsigned 16 bit                           0                         +65 535
unsigned 32 bit                           0                  +4 294 967 295
unsigned 64 bit                           0     +18 446 744 073 709 551 615

In Java, the Java Language Specification determines the representation of the data types.

The order is: byte 8 bits, short 16 bits, int 32 bits, long 64 bits. All of these types are signed, there are no unsigned versions. However, bit manipulations treat the numbers as they were unsigned (that is, handling all bits correctly).

The character data type char is 16 bits wide, unsigned, and holds characters using UTF-16 encoding (however, it is possible to assign a char an arbitrary unsigned 16 bit integer that represents an invalid character codepoint)

          width                     minimum                         maximum

SIGNED
byte:     8 bit                        -128                            +127
short:   16 bit                     -32 768                         +32 767
int:     32 bit              -2 147 483 648                  +2 147 483 647
long:    64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807

UNSIGNED
char     16 bit                           0                         +65 535

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);

SQL Case Expression Syntax?

I dug up the Oracle page for the same and it looks like this is the same syntax, just described slightly different.

Link: Oracle/PLSQL: Case Statement

SQL sum with condition

With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.

SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch 
AND t1.transID = t2.transID
AND ValueDate > @startMonthDate HAVING money > 0;

How to load GIF image in Swift?

//
//  iOSDevCenters+GIF.swift
//  GIF-Swift
//
//  Created by iOSDevCenters on 11/12/15.
//  Copyright © 2016 iOSDevCenters. All rights reserved.
//
import UIKit
import ImageIO


extension UIImage {

public class func gifImageWithData(data: NSData) -> UIImage? {
    guard let source = CGImageSourceCreateWithData(data, nil) else {
        print("image doesn't exist")
        return nil
    }

    return UIImage.animatedImageWithSource(source: source)
}

public class func gifImageWithURL(gifUrl:String) -> UIImage? {
    guard let bundleURL = NSURL(string: gifUrl)
        else {
            print("image named \"\(gifUrl)\" doesn't exist")
            return nil
    }
    guard let imageData = NSData(contentsOf: bundleURL as URL) else {
        print("image named \"\(gifUrl)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

public class func gifImageWithName(name: String) -> UIImage? {
    guard let bundleURL = Bundle.main
        .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
    }

    guard let imageData = NSData(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
    var delay = 0.1

    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
    let gifProperties: CFDictionary = unsafeBitCast(CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self)

    var delayObject: AnyObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self)

    if delayObject.doubleValue == 0 {
        delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
    }

    delay = delayObject as! Double

    if delay < 0.1 {
        delay = 0.1
    }

    return delay
}

class func gcdForPair(a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    if a! < b! {
        let c = a!
        a = b!
        b = c
    }

    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b!
        } else {
            a = b!
            b = rest
        }
    }
}

class func gcdForArray(array: Array<Int>) -> Int {
    if array.isEmpty {
        return 1
    }

    var gcd = array[0]

    for val in array {
        gcd = UIImage.gcdForPair(a: val, gcd)
    }

    return gcd
}

class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
    let count = CGImageSourceGetCount(source)
    var images = [CGImage]()
    var delays = [Int]()

    for i in 0..<count {
        if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
            images.append(image)
        }

        let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    let gcd = gcdForArray(array: delays)
    var frames = [UIImage]()

    var frame: UIImage
    var frameCount: Int
    for i in 0..<count {
        frame = UIImage(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }

    let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)

    return animation
}
}

Here is the file updated for Swift 3

How to get UTC timestamp in Ruby?

time = Time.zone.now()

It will work as

irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC

How to make html table vertically scrollable

Hi try with this overflow-y: scroll. I hope it may helps you

TypeError: $.browser is undefined

Replace your jquery files with followings :

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

Find files in a folder using Java

Have a look at java.io.File.list() and FilenameFilter.

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

In Java, how do I get the difference in seconds between 2 dates?

There is no such class as DateTime in the standard Java SE API. Although there is one in joda-time, even that does not have a daysBetween method.

Using the standard Java API, the easiest way to get seconds between two java.util.Date objects would be to subtract their timestamps and divide by 1000:

int secondsBetween = (date1.getTime() - date2.getTime()) / 1000;

How to Find the Default Charset/Encoding in Java?

First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?

You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html

When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.

I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.

But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.

LINQ Aggregate algorithm explained

This is an explanation about using Aggregate on a Fluent API such as Linq Sorting.

var list = new List<Student>();
var sorted = list
    .OrderBy(s => s.LastName)
    .ThenBy(s => s.FirstName)
    .ThenBy(s => s.Age)
    .ThenBy(s => s.Grading)
    .ThenBy(s => s.TotalCourses);

and lets see we want to implement a sort function that take a set of fields, this is very easy using Aggregate instead of a for-loop, like this:

public static IOrderedEnumerable<Student> MySort(
    this List<Student> list,
    params Func<Student, object>[] fields)
{
    var firstField = fields.First();
    var otherFields = fields.Skip(1);

    var init = list.OrderBy(firstField);
    return otherFields.Skip(1).Aggregate(init, (resultList, current) => resultList.ThenBy(current));
}

And we can use it like this:

var sorted = list.MySort(
    s => s.LastName,
    s => s.FirstName,
    s => s.Age,
    s => s.Grading,
    s => s.TotalCourses);

Create a folder inside documents folder in iOS apps

The Swift 2 solution:

let documentDirectoryPath: String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
if !NSFileManager.defaultManager().fileExistsAtPath(documentDirectoryPath) {
        do {
            try NSFileManager.defaultManager().createDirectoryAtPath(documentDirectoryPath, withIntermediateDirectories: false, attributes: nil)

        } catch let createDirectoryError as NSError {
            print("Error with creating directory at path: \(createDirectoryError.localizedDescription)")
        }

    }

Node.js + Nginx - What now?

You can also setup multiple domain with nginx, forwarding to multiple node.js processes.

For example to achieve these:

These ports (4000 and 5000) should be used to listen the app requests in your app code.

/etc/nginx/sites-enabled/domain1

server {
    listen 80;
    listen [::]:80;
    server_name domain1.com;
    access_log /var/log/nginx/domain1.access.log;
    location / {
        proxy_pass    http://127.0.0.1:4000/;
    }
}

In /etc/nginx/sites-enabled/domain2

server {
    listen 80;
    listen [::]:80;
    server_name domain2.com;
    access_log /var/log/nginx/domain2.access.log;
    location / {
        proxy_pass    http://127.0.0.1:5000/;
    }
}

Java method to sum any number of ints

If your using Java8 you can use the IntStream:

int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());

Results: 181

Just 1 line of code which will sum the array.

How to replace sql field value

To avoid update names that contain .com like [email protected] to [email protected], you can do this:

UPDATE Yourtable
SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')

How is Docker different from a virtual machine?

Docker encapsulates an application with all its dependencies.

A virtualizer encapsulates an OS that can run any applications it can normally run on a bare metal machine.

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

Java - Convert image to Base64

To begin with, this line of code:

while ((bytesRead = fis.read(byteArray)) != -1)

is equivalent to

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)

So it's writing into the byteArray from offset 0, rather than from where you wrote to before.

You need something like this:

int offset = 0;
int bytesRead = 0;

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
    offset += bytesRead;
}

After you have read the data (bytes) in then, you can convert it to Base64.

There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.

I would ditch the byte array and go with something like this:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);

Or condense it further as Thilo has with FileUtils.

Getting value from table cell in JavaScript...not jQuery

confer below code


<html>
<script>


    function addRow(){
 var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e =table.rows.length-1;
var l =table.rows[e].cells.length;
//x.innerHTML = "&nbsp;";
 for (var c =0,  m=l; c < m; c++) {
table.rows[0].insertCell(c);
   table.rows[0].cells[c].innerHTML  = "&nbsp;&nbsp;";
}

}




function addColumn(){
       var table = document.getElementById('myTable');
        for (var r = 0, n = table.rows.length; r < n; r++) {
                table.rows[r].insertCell(0);
                table.rows[r].cells[0].innerHTML =  "&nbsp;&nbsp;" ;

        }

    }

function deleteRow() {
    document.getElementById("myTable").deleteRow(0);

}

function deleteColumn() {
   // var row = document.getElementById("myRow");
 var table = document.getElementById('myTable');
 for (var r = 0, n = table.rows.length; r < n; r++) {
    table.rows[r].deleteCell(0);//var table handle 
}
}

</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0       style='cursor:hand'>
    <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
    <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
    <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>

    <table  id='myTable' border=1 cellpadding=0 cellspacing=0>
 <tr id='myRow'>          
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
<tr>          
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>

    </table>



</body>
</html>

Can't import javax.servlet.annotation.WebServlet

Check that the version number of your servlet-api.jar is at least 3.0. There is a version number inside the jar in the META-INF/manifest.mf file:

Implementation-Version: 3.0.1

If it's less than 3.0 download the 3.0.1 from Maven Central: http://search.maven.org/#artifactdetails|javax.servlet|javax.servlet-api|3.0.1|jar

Former servlet specifications (2.5, 2.4 etc.) do not support annotations.

Making button go full-width?

In Bootstrap 5, the class btn-block doesn't work anymore. But instead, you can add the class w-100 to the button to make it as wide as its container.

_x000D_
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="row"><div class=" col-5 ">
            <a class="btn btn-outline-primary w-100  " href="# "><span>Button 1</span></a> 
</div><div class="col-5 ">

            <a class=" btn btn-primary w-100 weiss " href="# "><span>Button 2</span></a> 
</div></div>
_x000D_
_x000D_
_x000D_

How do I copy a string to the clipboard?

I didn't have a solution, just a workaround.

Windows Vista onwards has an inbuilt command called clip that takes the output of a command from command line and puts it into the clipboard. For example, ipconfig | clip.

So I made a function with the os module which takes a string and adds it to the clipboard using the inbuilt Windows solution.

import os
def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)

# Example
addToClipBoard('penny lane')

# Penny Lane is now in your ears, eyes, and clipboard.

As previously noted in the comments however, one downside to this approach is that the echo command automatically adds a newline to the end of your text. To avoid this you can use a modified version of the command:

def addToClipBoard(text):
    command = 'echo | set /p nul=' + text.strip() + '| clip'
    os.system(command)

If you are using Windows XP it will work just following the steps in Copy and paste from Windows XP Pro's command prompt straight to the Clipboard.

How can I reload .emacs after changing it?

Here is a quick and easy way to quick test your config. You can also use C-x C-e at the end of specific lisp to execute certain function individually.

C-x C-e runs the command eval-last-sexp (found in global-map), which is an interactive compiled Lisp function.

It is bound to C-x C-e.

(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)

Evaluate sexp before point; print value in the echo area. Interactively, with prefix argument, print output into current buffer.

Normally, this function truncates long output according to the value of the variables ‘eval-expression-print-length’ and ‘eval-expression-print-level’. With a prefix argument of zero, however, there is no such truncation. Such a prefix argument also causes integers to be printed in several additional formats (octal, hexadecimal, and character).

If ‘eval-expression-debug-on-error’ is non-nil, which is the default, this command arranges for all errors to enter the debugger.

POST JSON to API using Rails and HTTParty

The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)

query_string_normalizer: ->(query){query.to_json}

How to use an environment variable inside a quoted string in Bash

Just a quick note/summary for any who came here via Google looking for the answer to the general question asked in the title (as I was). Any of the following should work for getting access to shell variables inside quotes:

echo "$VARIABLE"
echo "${VARIABLE}"

Use of single quotes is the main issue. According to the Bash Reference Manual:

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. [...] Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

In the specific case asked in the question, $COLUMNS is a special variable which has nonstandard properties (see lhunath's answer above).

Hide HTML element by id

I found that the following code, when inserted into the site's footer, worked well enough:

<script type="text/javascript">
$("#nav-ask").remove();
</script>

This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

Have a look at ImmutableMap JavaDoc: doc

There is information about that there:

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

Android Studio Image Asset Launcher Icon Background Color

First, create a launcher icon (Adaptive and Legacy) from Image Asset:

Select an image for background layer and resize it to 0% or 1% and In legacy tab set shape to none.

Then, delete folder res/mipmap/ic_laucher_round in the project window and Open AndroidManifest.xml and remove attribute android:roundIcon="@mipmap/ic_launcher_round" from the application element.

In the end, delete ic_launcher.xml from mipmap-anydpi-v26.

Notice that: Some devices like Nexus 5X (Android 8.1) adding a white background automatically and can't do anything.

Get child Node of another Node, given node name

If the Node is not just any node, but actually an Element (it could also be e.g. an attribute or a text node), you can cast it to Element and use getElementsByTagName.

Is there a way to include commas in CSV columns without breaking the formatting?

You need to quote that values.
Here is a more detailed spec.

How to skip over an element in .map()?

Just .filter() it first:

var sources = images.filter(function(img) {
  if (img.src.split('.').pop() === "json") {
    return false; // skip
  }
  return true;
}).map(function(img) { return img.src; });

If you don't want to do that, which is not unreasonable since it has some cost, you can use the more general .reduce(). You can generally express .map() in terms of .reduce:

someArray.map(function(element) {
  return transform(element);
});

can be written as

someArray.reduce(function(result, element) {
  result.push(transform(element));
  return result;
}, []);

So if you need to skip elements, you can do that easily with .reduce():

var sources = images.reduce(function(result, img) {
  if (img.src.split('.').pop() !== "json") {
    result.push(img.src);
  }
  return result;
}, []);

In that version, the code in the .filter() from the first sample is part of the .reduce() callback. The image source is only pushed onto the result array in the case where the filter operation would have kept it.

update — This question gets a lot of attention, and I'd like to add the following clarifying remark. The purpose of .map(), as a concept, is to do exactly what "map" means: transform a list of values into another list of values according to certain rules. Just as a paper map of some country would seem weird if a couple of cities were completely missing, a mapping from one list to another only really makes sense when there's a 1 to 1 set of result values.

I'm not saying that it doesn't make sense to create a new list from an old list with some values excluded. I'm just trying to make clear that .map() has a single simple intention, which is to create a new array of the same length as an old array, only with values formed by a transformation of the old values.

How to close existing connections to a DB

In more recent versions of SQL Server Management studio, you can now right click on a database and 'Take Database Offline'. This gives you the option to Drop All Active Connections to the database.

Confirm Password with jQuery Validate

jQuery('.validatedForm').validate({
        rules : {
            password : {
                minlength : 5
            },
            password_confirm : {
                minlength : 5,
                equalTo : '[name="password"]'
            }
        }

In general, you will not use id="password" like this. So, you can use [name="password"] instead of "#password"

ng-mouseover and leave to toggle item using mouse in angularjs

I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)

<ul ng-repeat="task in tasks">
    <li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
    <span ng-show="hoverEdit"><a>Edit</a></span>
</ul>

Rails: call another controller action from a controller

Separate these functions from controllers and put them into model file. Then include the model file in your controller.

Installing Java 7 on Ubuntu

I think you should consider Java installation procedure carefully. Following is the detailed process which covers almost all possible failures.

Installing Java with apt-get is easy. First, update the package index:

sudo apt-get update

Then, check if Java is not already installed:

java -version

If it returns "The program java can be found in the following packages", Java hasn't been installed yet, so execute the following command:

sudo apt-get install default-jre

You are fine till now as I assume.

This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), which is usually needed to compile Java applications (for example Apache Ant, Apache Maven, Eclipse and IntelliJ IDEA execute the following command:

sudo apt-get install default-jdk

That is everything that is needed to install Java.

Installing OpenJDK 7:

To install OpenJDK 7, execute the following command:

sudo apt-get install openjdk-7-jre 

This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), execute the following command:

sudo apt-get install openjdk-7-jdk

Installing Oracle JDK:

The Oracle JDK is the official JDK; however, it is no longer provided by Oracle as a default installation for Ubuntu.

You can still install it using apt-get. To install any version, first execute the following commands:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

Then, depending on the version you want to install, execute one of the following commands:

Oracle JDK 7:

sudo apt-get install oracle-java7-installer

Oracle JDK 8:

sudo apt-get install oracle-java8-installer

Only mkdir if it does not exist

Use mkdir's -p option, but note that it has another effect as well.

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

Good ways to sort a queryset? - Django

Here's a way that allows for ties for the cut-off score.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.

ssh remote host identification has changed

AWS EC2.

Find the ip in the message it gives you.

run

vim /home/ec2-user/.ssh/known_hosts

Use the arrow keys to find the ip from the message and click.

dd

This will delete that line then run escape

:wp

This will save then you are good to go.

Should we @Override an interface's method implementation?

For me, often times this is the only reason some code requires Java 6 to compile. Not sure if it's worth it.

libpng warning: iCCP: known incorrect sRGB profile

Solution

The incorrect profile could be fixed by:

  1. Opening the image with the incorrect profile using QPixmap::load
  2. Saving the image back to the disk (already with the correct profile) using QPixmap::save

Note: This solution uses the Qt Library.

Example

Here is a minimal example I have written in C++ in order to demonstrate how to implement the proposed solution:

QPixmap pixmap;
pixmap.load("badProfileImage.png");

QFile file("goodProfileImage.png");
file.open(QIODevice::WriteOnly);
pixmap.save(&file, "PNG");

The complete source code of a GUI application based on this example is available on GitHub.

UPDATE FROM 05.12.2019: The answer was and is still valid, however there was a bug in the GUI application I have shared on GitHub, causing the output image to be empty. I have just fixed it and apologise for the inconvenience!

What does "yield break;" do in C#?

It specifies that an iterator has come to an end. You can think of yield break as a return statement which does not return a value.

For example, if you define a function as an iterator, the body of the function may look like this:

for (int i = 0; i < 5; i++)
{
    yield return i;
}

Console.Out.WriteLine("You will see me");

Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.

Or like this with yield break:

int i = 0;
while (true)
{
    if (i < 5)
    {
        yield return i;
    }
    else
    {
        // note that i++ will not be executed after this
        yield break;
    }
    i++;
}

Console.Out.WriteLine("Won't see me");

In this case the last statement is never executed because we left the function early.

wget command to download a file and save as a different filename

Also notice the order of parameters on the command line. At least on some systems (e.g. CentOS 6):

wget -O FILE URL

works. But:

wget URL -O FILE

does not work.

Delete all lines starting with # or ; in Notepad++

Find:

^[#;].*

Replace with nothing. The ^ indicates the start of a line, the [#;] is a character class to match either # or ;, and .* matches anything else in the line.

In versions of Notepad++ before 6.0, you won't be able to actually remove the lines due to a limitation in its regex engine; the replacement results in blank lines for each line matched. In other words, this:

# foo
; bar
statement;

Will turn into:



statement;

However, the replacement will work in Notepad++ 6.0 if you add \r, \n or \r\n to the end of the pattern, depending on which line ending your file is using, resulting in:

statement;

SQL Server 2005 Setting a variable to the result of a select query

You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

Incidentally, since you are using a predicate like this:

CONVERT(...) = CONVERT(...)

that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

Here is one way to make the original query somewhat better:

DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  FF.FaultDate >= @ooDate AND
  FF.FaultDate < DATEADD(day, 1, @ooDate) AND
  OFIO.OutageID = 1

This version could leverage in index that involved FaultDate, and achieves the same goal.

Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

SELECT 
  COUNT(FF.HALID)
FROM
  Outages.FaultsInOutages AS OFIO 
  INNER JOIN Faults.Faults as FF ON 
    FF.HALID = OFIO.HALID 
WHERE
  CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
  OFIO.OutageID = 1

Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

Regards.

How to strip comma in Python string

Use replace method of strings not strip:

s = s.replace(',','')

An example:

>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo  bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True

Remote JMX connection

In my testing with Tomcat and Java 8, the JVM was opening an ephemeral port in addition to the one specified for JMX. The following code fixed me up; give it a try if you are having issues where your JMX client (e.g. VisualVM is not connecting.

-Dcom.sun.management.jmxremote.port=8989
-Dcom.sun.management.jmxremote.rmi.port=8989

Also see Why Java opens 3 ports when JMX is configured?

Iterate over object keys in node.js

For simple iteration of key/values, sometimes libraries like underscorejs can be your friend.

const _ = require('underscore');

_.each(a, function (value, key) {
    // handle
});

just for reference

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

pthread function from a class

The above answers are good, but in my case, 1st approach that converts the function to be a static didn't work. I was trying to convert exiting code to move into thread function but that code had lots to references to non-static class members already. The second solution of encapsulating into C++ object works, but has 3-level wrappers to run a thread.

I had an alternate solution that uses existing C++ construct - 'friend' function, and it worked perfect for my case. An example of how I used 'friend' (will use the above same example for names showing how it can be converted into a compact form using friend)

    class MyThreadClass
    {
    public:
       MyThreadClass() {/* empty */}
       virtual ~MyThreadClass() {/* empty */}

       bool Init()
       {
          return (pthread_create(&_thread, NULL, &ThreadEntryFunc, this) == 0);
       }

       /** Will not return until the internal thread has exited. */
       void WaitForThreadToExit()
       {
          (void) pthread_join(_thread, NULL);
       }

    private:
       //our friend function that runs the thread task
       friend void* ThreadEntryFunc(void *);

       pthread_t _thread;
    };

    //friend is defined outside of class and without any qualifiers
    void* ThreadEntryFunc(void *obj_param) {
    MyThreadClass *thr  = ((MyThreadClass *)obj_param); 

    //access all the members using thr->

    return NULL;
    }

Ofcourse, we can use boost::thread and avoid all these, but I was trying to modify the C++ code to not use boost (the code was linking against boost just for this purpose)

returning a Void object

It is possible to create instances of Void if you change the security manager, so something like this:

static Void getVoid() throws SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    class BadSecurityManager extends SecurityManager {
    
        @Override
        public void checkPermission(Permission perm) { }
    
        @Override
        public void checkPackageAccess(String pkg) { }

    }
    System.setSecurityManager(badManager = new BadSecurityManager());
    Constructor<?> constructor = Void.class.getDeclaredConstructors()[0];
    if(!constructor.isAccessible()) {
        constructor.setAccessible(true);
    }
    return (Void) constructor.newInstance();
}

Obviously this is not all that practical or safe; however, it will return an instance of Void if you are able to change the security manager.

.NET / C# - Convert char[] to string

Use the string constructor which accepts chararray as argument, start position and length of array. Syntax is given below:

string charToString = new string(CharArray, 0, CharArray.Count());

Toggle Class in React

refs is not a DOM element. In order to find a DOM element, you need to use findDOMNode menthod first.

Do, this

var node = ReactDOM.findDOMNode(this.refs.btn);
node.classList.toggle('btn-menu-open');

alternatively, you can use like this (almost actual code)

this.state.styleCondition = false;


<a ref="btn" href="#" className={styleCondition ? "btn-menu show-on-small" : ""}><i></i></a>

you can then change styleCondition based on your state change conditions.

How to delete a certain row from mysql table with same column values?

You must add an id that auto-increment for each row, after that you can delet the row by its id. so your table will have an unique id for each row and the id_user, id_product ecc...

No Multiline Lambda in Python: Why not?

(For anyone still interested in the topic.)

Consider this (includes even usage of statements' return values in further statements within the "multiline" lambda, although it's ugly to the point of vomiting ;-)

>>> def foo(arg):
...     result = arg * 2;
...     print "foo(" + str(arg) + ") called: " + str(result);
...     return result;
...
>>> f = lambda a, b, state=[]: [
...     state.append(foo(a)),
...     state.append(foo(b)),
...     state.append(foo(state[0] + state[1])),
...     state[-1]
... ][-1];
>>> f(1, 2);
foo(1) called: 2
foo(2) called: 4
foo(6) called: 12
12

Should each and every table have a primary key?

If you are using Hibernate its not possible to create an Entity without a primary key. This issues can create problem if you are working with an existing database which was created with plain sql/ddl scripts, and no primary key was added

How to avoid 'undefined index' errors?

Figure out what keys are in the $output array, and fill the missing ones in with empty strings.

$keys = array_keys($output);
$desired_keys = array('author', 'new_icon', 'admin_link', 'etc.');

foreach($desired_keys as $desired_key){
   if(in_array($desired_key, $keys)) continue;  // already set
   $output[$desired_key] = '';
}

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

Why does npm install say I have unmet dependencies?

npm install will install all the packages from npm-shrinkwrap.json, but might ignore packages in package.json, if they're not preset in the former.

If you're project has a npm-shrinkwrap.json, make sure you run npm shrinkwrap to regenerate it, each time you add add/remove/change package.json.

python dataframe pandas drop column using int

You can use the following line to drop the first two columns (or any column you don't need):

df.drop([df.columns[0], df.columns[1]], axis=1)

Reference

Get individual query parameters from Uri

I had to do this for a modern windows app. I used the following:

public static class UriExtensions
{
    private static readonly Regex _regex = new Regex(@"[?&](\w[\w.]*)=([^?&]+)");

    public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
    {
        var match = _regex.Match(uri.PathAndQuery);
        var paramaters = new Dictionary<string, string>();
        while (match.Success)
        {
            paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
            match = match.NextMatch();
        }
        return paramaters;
    }
}

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true

In Sender

  1. Declare params to be sent. We can send String, Object,…

Sender.xhtml

<f:metadata>
      <f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
  1. We’re going send param ID, it will be included with “includeViewParams=true” in return String of click button event Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrData

Sender.xhtml

<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
      <p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??" 
      ajax="false"/>
</p:dataTable>

In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID

Sender_MB.java
    public String clickBtnDetail(sender_DTO sender_dto) {
        this._strID = sender_dto.getStrID();
        return "Receiver?faces-redirect=true&includeViewParams=true";
    }

The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*

In Recever

  1. Get viewParam Receiver.xhtml In Receiver we declare f:viewParam to get param from get request (receive), the name of param of receiver must be the same with sender (page)

Receiver.xhtml

<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>

It will get param ID from sender View and assign to receiver_MB._strID

  1. Use viewParam In Receiver, we want to use this param in sql query before the page render, so that we use preRenderView event. We are not going to use constructor because constructor will be invoked before viewParam is received So that we add

Receiver.xhtml

<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />

into f:metadata tag

Receiver.xhtml

<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
            type="preRenderView" />
</f:metadata>

Now we want to use this param in our read database method, it is available to use

Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
        if (FacesContext.getCurrentInstance().isPostback()) {
            return;
        }
        readFromDatabase();
    }
private void readFromDatabase() {
//use _strID to read and set property   
}

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

What is "406-Not Acceptable Response" in HTTP?

In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :

[Produces("application/xml")]
public class MyController : ControllerBase {...}

Thank you for putting me on the path !

ng serve not detecting file changes automatically

In your project dist folder is own by root

Try to use sudo ng serve instead of ng serve.

Another solution

When there is having a large number of files watch not work in linux.There is a Limit at INotify Watches on Linux. So increasing the watches limit

//When live server not work in linux

sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system

ng serve //You can also do sudo **ng serve**

How to restart adb from root to user mode?

For quick steps just check summary. If interested to know details, go on to read below.

adb is a daemon. Doing ps adb we can see its process.

shell@grouper:/ $ ps adb
USER     PID   PPID  VSIZE  RSS     WCHAN    PC        NAME
shell     133   1     4636   212   ffffffff 00000000 S /sbin/adbd

I just checked what additional property variables it is using when adb is running as root and user.

adb user mode :

shell@grouper:/ $ getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

adb root mode :

shell@grouper:/ # getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[service.adb.root]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

We can see that service.adb.root is a new prop variable that came up when we did adb root.

So, to change back adb to user from root, I went ahead and made this 0

setprop service.adb.root 0

But this did not change anything.

Then I went ahead and killed the process (with an intention to restart the process). The pid of adbd process in my device is 133

kill -9 133

I exited from shell automatically after I had killed the process.

I did adb shell again it was in user mode.

SUMMARY :

So, we have 3 very simple steps.

  1. Enter adb shell as a root.
  2. setprop service.adb.root 0
  3. kill -9 (pid of adbd)

After these steps just re-enter the shell with adb shell and you are back on your device as a user.

What is the difference between dict.items() and dict.iteritems() in Python2?

It's part of an evolution.

Originally, Python items() built a real list of tuples and returned that. That could potentially take a lot of extra memory.

Then, generators were introduced to the language in general, and that method was reimplemented as an iterator-generator method named iteritems(). The original remains for backwards compatibility.

One of Python 3’s changes is that items() now return views, and a list is never fully built. The iteritems() method is also gone, since items() in Python 3 works like viewitems() in Python 2.7.

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.

You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.

UPDATE 1:

ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.

If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

So it's all about what will happen when you delete rows from Parent table not from child table.

So in your case when user removes entries from CATs table then rows will be deleted from books table. :)

Hope this helps you :)

Change Default branch in gitlab

See also GitLab 13.6 (November 2020)

Customize the initial branch name for new projects within a group

When creating a new Git repository, the first branch created is named master by default.

In coordination with the Git project, broader community, and other Git vendors, GitLab has been listening to the development community’s feedback on determining a more descriptive and inclusive name for the default branch, and is now offering users options to change the name of the default branch name for their repositories.

Previously, we shipped the ability to customize the initial branch name at the instance-level and as part of 13.6, GitLab now allows group administrators to configure the default branch name for new repositories created through the GitLab interface.

See Documentation and Issue.

https://gitlab.com/gitlab-org/gitlab/uploads/2959ef65431bf4ffac659992360d6d8d/image.png


GitLab 13.9 (Feb 2021) details:

Git default branch name change

Every Git repository has an initial branch. It’s the first branch to be created automatically when you create a new repository.
By default, this initial branch is named master.

Git version 2.31.0 (scheduled for release March 15, 2021) will change the default branch name in Git from master to main.

In coordination with the Git project and the broader community, GitLab will be changing the default branch name for new projects on both our SaaS (GitLab.com) and self-managed offerings starting with GitLab 14.0.
This will not affect existing projects.

For more information, see the related epic and the Git mailing list discussion.

Deprecation date: Apr 22, 2021

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Surprise to see no one mentioned about event.preventDefault()

$("input[type=file]").mouseover(function(event) {
    event.preventDefault();
    // This will disable the default behavior of browser
 });

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.

NotSupportedException: Specified method is not supported. 

For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:

public async Task<IActionResult> Index(WebhookRequest request)
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // this won't fix your string empty problems
    // because exception will be thrown
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var body = await reader.ReadToEndAsync();

    // Do stuff
}

You'll need to take your model binding out of the method parameters, and manually bind yourself:

public async Task<IActionResult> Index()
{
    using var reader = new StreamReader(HttpContext.Request.Body);

    // You shouldn't need this line anymore.
    // reader.BaseStream.Seek(0, SeekOrigin.Begin);

    // You now have the body string raw
    var body = await reader.ReadToEndAsync();

    // As well as a bound model
    var request = JsonConvert.DeserializeObject<WebhookRequest>(body);
}

It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...

How to get the pure text without HTML element using JavaScript?

Depending on what you need, you can use either element.innerText or element.textContent. They differ in many ways. innerText tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent sort of just strips the html tags and gives you what's left.

innerText is not just used for IE anymore, and it is supported in all major browsers. Of course, unlike textContent, it has compatability with old IE browsers (since they came up with it).

Complete example (from Gabi's answer):

var element = document.getElementById('txt');
var text = element.innerText || element.textContent; // or element.textContent || element.innerText
element.innerHTML = text;

How to reset (clear) form through JavaScript?

Use JavaScript function reset():

document.forms["frm_id"].reset();

Read only the first line of a file?

first_line = next(open(filename))

message box in jquery

using jQuery UI you can use the dialog that offers. More information at http://docs.jquery.com/UI/Dialog

How to preSelect an html dropdown list with php?

<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">

This is a very simple and straightforward way, if I understand your question correctly.

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

It sounds like a classpath issue, so there are a few different ways to go about it. Where does org/hamcret/SelfDescribing come from? Is that your class or in a different jar?

Try going to your project Build Path and on the Libraries tab, add a Library. You should be able to choose JUnit to your project. This is a little bit different than just having the JUnit jar file In your project.

In your Run Configuration for the JUnit test, check the Classpath. You could probably fix this by adding making sure your Classpath can see that SelfDescribing class there. The Run option in Eclipse has a different set of options for the JUnit options.

How can I commit files with git?

It looks like all of the edits are already a part of the index. So to commit just use the commit command

git commit -m "My Commit Message"

Looking at your messages though my instinct says that you probably don't want the cache files to be included in your depot. Especially if it something that is built on the fly when running your program. If so then you should add the following line to your .gitignore file

httpdocs/newsite/manifest/cache/*

How to determine whether a substring is in a different string

You can also try find() method. It determines if string str occurs in string, or in a substring of string.

str1 = "please help me out so that I could solve this"
str2 = "please help me out"

if (str1.find(str2)>=0):
  print("True")
else:
  print ("False")

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

how do I initialize a float to its max/min value?

May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?

Default SecurityProtocol in .NET 4.5

For completeness, here is a Powershell script that sets aforementioned registry keys:

new-itemproperty -path "HKLM:\SOFTWARE\Microsoft\.NETFramework\v4.0.30319" -name "SchUseStrongCrypto" -Value 1 -PropertyType "DWord";
new-itemproperty -path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319" -name "SchUseStrongCrypto" -Value 1 -PropertyType "DWord"

How to set a Javascript object values dynamically?

When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.

You can access these dictionaries in two ways:

  • Like an array (e.g. myObj[name]); or
  • Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.

You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.

myObj["name"]

Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.

How do I send a file as an email attachment using Linux command line?

I use SendEmail, which was created for this scenario. It's packaged for Ubuntu so I assume it's available

sendemail -f [email protected] -t [email protected] -m "Here are your files!" -a file1.jpg file2.zip

http://caspian.dotconf.net/menu/Software/SendEmail/

How to make Python speak

Just use this simple code in python.

Works only for windows OS.

from win32com.client import Dispatch

def speak(text):
    speak = Dispatch("SAPI.Spvoice")
    speak.Speak(text)

speak("How are you dugres?")

I personally use this.