Programs & Examples On #Scaling

Scaling refers to the image manipulation function of re-sizing an image. For issues to do with handling increasing workload gracefully in software or network components, see "scalabilty".

Android and setting width and height programmatically in dp units

Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:

final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);

And your dimens.xml will have:

<dimen name="dimen_entry_in_dp">72dp</dimen>

Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

How can I make an svg scale with its parent container?

You'll want to do a transform as such:

with JavaScript:

document.getElementById(yourtarget).setAttribute("transform", "scale(2.0)");

With CSS:

#yourtarget {
  transform:scale(2.0);
  -webkit-transform:scale(2.0);
}

Wrap your SVG Page in a Group tag as such and target it to manipulate the whole page:

<svg>
  <g id="yourtarget">
    your svg page
  </g>
</svg>

Note: Scale 1.0 is 100%

Image scaling causes poor quality in firefox/internet explorer but not chrome

Your problem is that you are relying on the browser to resize your images. Browsers have notoriously poor image scaling algorithms, which will cause the ugly pixelization.

You should resize your images in a graphics program first before you use them on the webpage.

Also, you have a spelling mistake: it should say moz-crisp-edges; however, that won't help you in your case (because that resizing algorithm won't give you a high quality resize: https://developer.mozilla.org/En/CSS/Image-rendering)

Android Webview - Webpage should fit the device screen

All you need to do is simply

webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);

How to scale down a range of numbers with a known min and max value

I sometimes find a variation of this useful.

  1. Wrapping the scale function in a class so that I do not need to pass around the min/max values if scaling the same ranges in several places
  2. Adding two small checks that ensures that the result value stays within the expected range.

Example in JavaScript:

class Scaler {
  constructor(inMin, inMax, outMin, outMax) {
    this.inMin = inMin;
    this.inMax = inMax;
    this.outMin = outMin;
    this.outMax = outMax;
  }

  scale(value) {
    const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;

    if (result < this.outMin) {
      return this.outMin;
    } else if (result > this.outMax) {
      return this.outMax;
    }

    return result;
  }
}

This example along with a function based version comes from the page https://writingjavascript.com/scaling-values-between-two-ranges

Can anyone explain me StandardScaler?

StandardScaler performs the task of Standardization. Usually a dataset contains variables that are different in scale. For e.g. an Employee dataset will contain AGE column with values on scale 20-70 and SALARY column with values on scale 10000-80000.
As these two columns are different in scale, they are Standardized to have common scale while building machine learning model.

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

How to get the class of the clicked element?

$("li").click(function(){
    alert($(this).attr("class"));
});

open link of google play store in mobile version android

You can use Android Intents library for opening your application page at Google Play like that:

Intent intent = IntentUtils.openPlayStore(getApplicationContext());
startActivity(intent);

git stash blunder: git stash pop and ended up with merge conflicts

See man git merge (HOW TO RESOLVE CONFLICTS):

After seeing a conflict, you can do two things:

  • Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git-reset --hard can be used for this.

  • Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.

And under TRUE MERGE (to see what 2. and 3. refers to):

When it is not obvious how to reconcile the changes, the following happens:

  1. The HEAD pointer stays the same.

  2. The MERGE_HEAD ref is set to point to the other branch head.

  3. Paths that merged cleanly are updated both in the index file and in your working tree.

  4. ...

So: use git reset --hard if you want to remove the stash changes from your working tree, or git reset if you want to just clean up the index and leave the conflicts in your working tree to merge by hand.

Under man git stash (OPTIONS, pop) you can read in addition:

Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.

Generate .pem file used to set up Apple Push Notifications

it is very simple after exporting the Cert.p12 and key.p12, Please find below command for the generating 'apns' .pem file.

https://www.sslshopper.com/ssl-converter.html ?

command to create apns-dev.pem from Cert.pem and Key.pem
?    

openssl rsa -in Key.pem -out apns-dev-key-noenc.pem
?    

cat Cert.pem apns-dev-key-noenc.pem > apns-dev.pem

Above command is useful for both Sandbox and Production.

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

How can I get list of values from dict?

There should be one - and preferably only one - obvious way to do it.

Therefore list(dictionary.values()) is the one way.

Yet, considering Python3, what is quicker?

[*L] vs. [].extend(L) vs. list(L)

small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}

print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())

print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())

big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}

print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())

print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.

# Name                    Version                   Build
ipython                   7.5.0            py37h24bf2e0_0

The result

  1. For small dictionaries * operator is quicker
  2. For big dictionaries where it matters list() is maybe slightly quicker

How to take a screenshot programmatically on iOS

In Swift you can use following code.

if UIScreen.mainScreen().respondsToSelector(Selector("scale")) {
    UIGraphicsBeginImageContextWithOptions(self.window!.bounds.size, false, UIScreen.mainScreen().scale)
}
else{
    UIGraphicsBeginImageContext(self.window!.bounds.size)
}
self.window?.layer.renderInContext(UIGraphicsGetCurrentContext())
var image : UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

Disable keyboard on EditText

// only if you completely want to disable keyboard for 
// that particular edit text
your_edit_text = (EditText) findViewById(R.id.editText_1);
your_edit_text.setInputType(InputType.TYPE_NULL);

How to generate a unique hash code for string input in android...?

It depends on what you mean:

  • As mentioned String.hashCode() gives you a 32 bit hash code.

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.

  • If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)

But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.

How do I run a PowerShell script when the computer starts?

Execute PowerShell command below to run the PowerShell script .ps1 through the task scheduler at user login.

Register-ScheduledTask -TaskName "SOME TASKNAME" -Trigger (New-ScheduledTaskTrigger -AtLogon) -Action (New-ScheduledTaskAction -Execute "${Env:WinDir}\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-WindowStyle Hidden -Command `"& 'C:\PATH\TO\FILE.ps1'`"") -RunLevel Highest -Force;

-AtLogOn - indicates that a trigger starts a task when a user logs on.

-AtStartup - indicates that a trigger starts a task when the system is started.

-WindowStyle Hidden - don't show PowerShell window at startup. Remove if not required.

-RunLevel Highest - run PowerShell as administrator. Remove if not required.

P.S.

If necessary execute PowerShell command below to enable PowerShell scripts execution.

Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy Unrestricted -Force;

Bypass - nothing is blocked and there are no warnings or prompts.

Unrestricted - loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the internet, you're prompted for permission before it runs.

Using a custom typeface in Android

I was able to do this in a centralized way, here is the result:

enter image description here

I have following Activity and I extend from it if I need custom fonts:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater.Factory;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class CustomFontActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    getLayoutInflater().setFactory(new Factory() {

        @Override
        public View onCreateView(String name, Context context,
                AttributeSet attrs) {
            View v = tryInflate(name, context, attrs);
            if (v instanceof TextView) {
                setTypeFace((TextView) v);
            }
            return v;
        }
    });
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

private View tryInflate(String name, Context context, AttributeSet attrs) {
    LayoutInflater li = LayoutInflater.from(context);
    View v = null;
    try {
        v = li.createView(name, null, attrs); 
    } catch (Exception e) {
        try {
            v = li.createView("android.widget." + name, null, attrs);
        } catch (Exception e1) {
        }
    }
    return v;
}

private void setTypeFace(TextView tv) {
    tv.setTypeface(FontUtils.getFonts(this, "MTCORSVA.TTF"));
}
}

But if I am using an activity from support package e.g. FragmentActivity then I use this Activity:

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class CustomFontFragmentActivity extends FragmentActivity {

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

// we can't setLayout Factory as its already set by FragmentActivity so we
// use this approach
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
    View v = super.onCreateView(name, context, attrs);
    if (v == null) {
        v = tryInflate(name, context, attrs);
        if (v instanceof TextView) {
            setTypeFace((TextView) v);
        }
    }
    return v;
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View onCreateView(View parent, String name, Context context,
        AttributeSet attrs) {
    View v = super.onCreateView(parent, name, context, attrs);
    if (v == null) {
        v = tryInflate(name, context, attrs);
        if (v instanceof TextView) {
            setTypeFace((TextView) v);
        }
    }
    return v;
}

private View tryInflate(String name, Context context, AttributeSet attrs) {
    LayoutInflater li = LayoutInflater.from(context);
    View v = null;
    try {
        v = li.createView(name, null, attrs);
    } catch (Exception e) {
        try {
            v = li.createView("android.widget." + name, null, attrs);
        } catch (Exception e1) {
        }
    }
    return v;
}

private void setTypeFace(TextView tv) {
    tv.setTypeface(FontUtils.getFonts(this, "MTCORSVA.TTF"));
}
}

I haven't tested this code with Fragments yet, but hopefully it will work.

My FontUtils is simple which also solves the pre-ICS issue mentioned here https://code.google.com/p/android/issues/detail?id=9904:

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Typeface;

public class FontUtils {

private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();

public static Typeface getFonts(Context context, String name) { 
    Typeface typeface = TYPEFACE.get(name);
    if (typeface == null) {
        typeface = Typeface.createFromAsset(context.getAssets(), "fonts/"
                + name);
        TYPEFACE.put(name, typeface);
    }
    return typeface;
}
}

How to parse JSON and access results

If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $json variable as an array:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff

References:

error LNK2005, already defined?

The linker tells you that you have the variable k defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k to use. In C++ you can have only one defintion of the same construct (variable, type, function).

To fix it, you will have to decide what your goal is

  • If you want to have two variables, both named k, you can use an anonymous namespace in both .cpp files, then refer to k as you are doing now:

.

namespace {
  int k;
}
  • You can rename one of the ks to something else, thus avoiding the duplicate defintion.
  • If you want to have only once definition of k and use that in both .cpp files, you need to declare in one as extern int k;, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern implies that the variable is defined in another compilation unit.

Why doesn't java.util.Set have get(int index)?

Please note only 2 basic data structure can be accessed via index.

  • Array data structure can be accessed via index with O(1) time complexity to achieve get(int index) operation.
  • LinkedList data structure can also be accessed via index, but with O(n) time complexity to achieve get(int index) operation.

In Java, ArrayList is implemented using Array data structure.

While Set data structure usually can be implemented via HashTable/HashMap or BalancedTree data structure, for fast detecting whether an element exists and add non-existing element, usually a well implemented Set can achieve O(1) time complexity contains operation. In Java, HashSet is the most common used implementation of Set, it is implemented by calling HashMap API, and HashMap is implemented using separate chaining with linked lists (a combination of Array and LinkedList).

Since Set can be implemented via different data structure, there is no get(int index) method for it.

HTML 5 Video "autoplay" not automatically starting in CHROME

This may not have been the case at the time the question was asked, but as of Chrome 66, autoplay is blocked.

http://bgr.com/2018/04/18/google-chrome-66-download-auto-playing-videos-block/

Windows service on Local Computer started and then stopped error

The account which is running the service might not have mapped the D:-drive (they are user-specific). Try sharing the directory, and use full UNC-path in your backupConfig.

Your watcher of type FileSystemWatcher is a local variable, and is out of scope when the OnStart method is done. You probably need it as an instance or class variable.

How to change a text with jQuery

Pretty straight forward to do:

$(function() {
  $('#toptitle').html('New word');
});

The html function accepts html as well, but its straight forward for replacing text.

how to check for datatype in node js- specifically for integer

I just made some tests in node.js v4.2.4 (but this is true in any javascript implementation):

> typeof NaN
'number'
> isNaN(NaN)
true
> isNaN("hello")
true

the surprise is the first one as type of NaN is "number", but that is how it is defined in javascript.

So the next test brings up unexpected result

> typeof Number("hello")
"number"

because Number("hello") is NaN

The following function makes results as expected:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));
}

AngularJS - ng-if check string empty value

If by "empty" you mean undefined, it is the way ng-expressions are interpreted. Then, you could use :

<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>

Download history stock prices automatically from yahoo finance in python

Extending @Def_Os's answer with an actual demo...

As @Def_Os has already said - using Pandas Datareader makes this task a real fun

In [12]: from pandas_datareader import data

pulling all available historical data for AAPL starting from 1980-01-01

#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')

# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')

first 5 rows

In [14]: aapl.head()
Out[14]:
                 Open       High     Low   Close     Volume  Adj Close
Date
1980-12-12  28.750000  28.875000  28.750  28.750  117258400   0.431358
1980-12-15  27.375001  27.375001  27.250  27.250   43971200   0.408852
1980-12-16  25.375000  25.375000  25.250  25.250   26432000   0.378845
1980-12-17  25.875000  25.999999  25.875  25.875   21610400   0.388222
1980-12-18  26.625000  26.750000  26.625  26.625   18362400   0.399475

last 5 rows

In [15]: aapl.tail()
Out[15]:
                 Open       High        Low      Close    Volume  Adj Close
Date
2016-06-07  99.250000  99.870003  98.959999  99.029999  22366400  99.029999
2016-06-08  99.019997  99.559998  98.680000  98.940002  20812700  98.940002
2016-06-09  98.500000  99.989998  98.459999  99.650002  26419600  99.650002
2016-06-10  98.529999  99.349998  98.480003  98.830002  31462100  98.830002
2016-06-13  98.690002  99.120003  97.099998  97.339996  37612900  97.339996

save all data as CSV file

In [16]: aapl.to_csv('d:/temp/aapl_data.csv')

d:/temp/aapl_data.csv - 5 first rows

Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...

Export DataTable to Excel with Open Xml SDK in c#

I wrote this quick example. It works for me. I only tested it with one dataset with one table inside, but I guess that may be enough for you.

Take into consideration that I treated all cells as String (not even SharedStrings). If you want to use SharedStrings you might need to tweak my sample a bit.

Edit: To make this work it is necessary to add WindowsBase and DocumentFormat.OpenXml references to project.

Enjoy,

private void ExportDataSet(DataSet ds, string destination)
        {
            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = workbook.AddWorkbookPart();

                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

                foreach (System.Data.DataTable table in ds.Tables) {

                    var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                    uint sheetId = 1;
                    if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                    {
                        sheetId =
                            sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                    }

                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
                    sheets.Append(sheet);

                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    List<String> columns = new List<string>();
                    foreach (System.Data.DataColumn column in table.Columns) {
                        columns.Add(column.ColumnName);

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }


                    sheetData.AppendChild(headerRow);

                    foreach (System.Data.DataRow dsrow in table.Rows)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (String col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }

                }
            }
        }

How does jQuery work when there are multiple elements with the same ID value?

Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this

$("[id=duplicatedId]")

You will get a collection with all elements with id=duplicatedId

How do I access named capturing groups in a .NET Regex?

Use the group collection of the Match object, indexing it with the capturing group name, e.g.

foreach (Match m in mc){
    MessageBox.Show(m.Groups["link"].Value);
}

java.io.StreamCorruptedException: invalid stream header: 7371007E

If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[] or List. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.

EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.

Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.

(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)

To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.

Close iOS Keyboard by touching anywhere using Swift

Use IQKeyboardmanager that will help you solve easy.....

/////////////////////////////////////////

![ how to disable the keyboard..][1]

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

   @IBOutlet weak var username: UITextField!
   @IBOutlet weak var password: UITextField!

   override func viewDidLoad() {
      super.viewDidLoad() 
      username.delegate = self
      password.delegate = self
      // Do any additional setup after loading the view, typically from a nib.
   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
   }

   func textFieldShouldReturn(textField: UITextField!) -> Bool // called when   'return' key pressed. return NO to ignore.
   {
      textField.resignFirstResponder()
      return true;
   }

   override func touchesBegan(_: Set<UITouch>, with: UIEvent?) {
     username.resignFirstResponder()
     password.resignFirstResponder()
     self.view.endEditing(true)
  }
}

img src SVG changing the styles with CSS

Why not create a webfont with your svg image or images, import the webfont in the css and then just change the color of the glyph using the css color attribute? No javascript needed

How to use ng-if to test if a variable is defined

Try this:

item.shipping!==undefined

Auto highlight text in a textbox control

I don't know why nobody mentioned that but you can also do this, it works for me

textbox.Select(0, textbox.Text.Length)

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Matlab: Running an m-file from command-line

Thanks to malat. Your comment helped me. But I want to add my try-catch block, as I found the MExeption method getReport() that returns the whole error message and prints it to the matlab console.

Additionally I printed the filename as this compilation is part of a batch script that calls matlab.

try
    some_code
    ...
catch message
    display(['ERROR in file: ' message.stack.file])
    display(['ERROR: ' getReport(message)])
end;

For a false model name passed to legacy code generation method, the output would look like:

ERROR in file: C:\..\..\..
ERROR: Undefined function or variable 'modelname'.

Error in sub-m-file (line 63)
legacy_code( 'slblock_generate', specs, modelname);

Error in m-file (line 11)
sub-m-file

Error in run (line 63)
evalin('caller', [script ';']);

Finally, to display the output at the windows command prompt window, just log the matlab console to a file with -logfile logfile.txt (use additionally -wait) and call the batch command type logfile.txt

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Bootstrap: how do I change the width of the container?

Set your own content container class with 1000px width property and then use container-fluid boostrap class instead of container.

Works but might not be the best solution.

How to get these two divs side-by-side?

Using flexbox it is super simple!

#parent_div_1, #parent_div_2, #parent_div_3 {
    display: flex;
}

Fiddle example

How to create a sleep/delay in nodejs that is Blocking?

I found something almost working here https://stackoverflow.com/questions/21819858/how-to-wrap-async-function-calls-into-a-sync-function-in-node-js-or-ja vascript

`function AnticipatedSyncFunction(){
    var ret;
    setTimeout(function(){
        var startdate = new Date()
        ret = "hello" + startdate;
    },3000);
    while(ret === undefined) {
       require('deasync').runLoopOnce();
    }
    return ret;    
}


var output = AnticipatedSyncFunction();
var startdate = new Date()
console.log(startdate)
console.log("output="+output);`

The unique problem is the date printed isn't correct but the process at least is sequential.

Execute Shell Script after post build in Jenkins

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

What is the difference between __str__ and __repr__?

To put it simply:

__str__ is used in to show a string representation of your object to be read easily by others.

__repr__ is used to show a string representation of the object.

Let's say I want to create a Fraction class where the string representation of a fraction is '(1/2)' and the object (Fraction class) is to be represented as 'Fraction (1,2)'

So we can create a simple Fraction class:

class Fraction:
    def __init__(self, num, den):
        self.__num = num
        self.__den = den

    def __str__(self):
        return '(' + str(self.__num) + '/' + str(self.__den) + ')'

    def __repr__(self):
        return 'Fraction (' + str(self.__num) + ',' + str(self.__den) + ')'



f = Fraction(1,2)
print('I want to represent the Fraction STRING as ' + str(f)) # (1/2)
print('I want to represent the Fraction OBJECT as ', repr(f)) # Fraction (1,2)

Angular 2 - NgFor using numbers instead collections

Please find attached my dynamic solution if you want to increase the size of an array dynamically after clicking on a button (This is how I got to this question).

Allocation of necessary variables:

  array = [1];
  arraySize: number;

Declare the function that adds an element to the array:

increaseArrayElement() {
   this.arraySize = this.array[this.array.length - 1 ];
   this.arraySize += 1;
   this.array.push(this.arraySize);
   console.log(this.arraySize);
}

Invoke the function in html

  <button md-button (click)="increaseArrayElement()" >
      Add element to array
  </button>

Iterate through array with ngFor:

<div *ngFor="let i of array" >
  iterateThroughArray: {{ i }}
</div>

How to get the day name from a selected date?

System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(System.DateTime.Now.DayOfWeek)

or

System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse("23/10/2009").DayOfWeek)

How to take complete backup of mysql database using mysqldump command line utility

To create dump follow below steps:

  1. Open CMD and go to bin folder where you have installed your MySQL
    ex:C:\Program Files\MySQL\MySQL Server 8.0\bin. If you see in this
    folder mysqldump.exe will be there. Or you have setup above folder in your Path variable of Environment Variable.

  2. Now if you hit mysqldump in CMD you can see CMD is able to identify dump command.

  3. Now run "mysqldump -h [host] -P [port] -u [username] -p --skip-triggers --no-create-info --single-transaction --quick --lock-tables=false ABC_databse > c:\xyz.sql"
  4. Above command will prompt for password then it will start processing.

Get absolute path to workspace directory in Jenkins Pipeline plugin

For me WORKSPACE was a valid property of the pipeline itself. So when I handed over this to a Groovy method as parameter context from the pipeline script itself, I was able to access the correct value using "... ${context.WORKSPACE} ..."

(on Jenkins 2.222.3, Build Pipeline Plugin 1.5.8, Pipeline: Nodes and Processes 2.35)

Javascript: console.log to html

This post has helped me a lot, and after a few iterations, this is what we use.

The idea is to post log messages and errors to HTML, for example if you need to debug JS and don't have access to the console.

You do need to change 'console.log' with 'logThis', as it is not recommended to change native functionality.

What you'll get:

  • A plain and simple 'logThis' function that will display strings and objects along with current date and time for each line
  • A dedicated window on top of everything else. (show it only when needed)
  • Can be used inside '.catch' to see relevant errors from promises.
  • No change of default console.log behavior
  • Messages will appear in the console as well.

_x000D_
_x000D_
function logThis(message) {
  // if we pass an Error object, message.stack will have all the details, otherwise give us a string
  if (typeof message === 'object') {
    message = message.stack || objToString(message);
  }

  console.log(message);

  // create the message line with current time
  var today = new Date();
  var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
  var time = today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
  var dateTime = date + ' ' + time + ' ';

  //insert line
  document.getElementById('logger').insertAdjacentHTML('afterbegin', dateTime + message + '<br>');
}

function objToString(obj) {
  var str = 'Object: ';
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      str += p + '::' + obj[p] + ',\n';
    }
  }
  return str;
}

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

logThis(object1)
logThis('And all the roads we have to walk are winding, And all the lights that lead us there are blinding')
_x000D_
#logWindow {
  overflow: auto;
  position: absolute;
  width: 90%;
  height: 90%;
  top: 5%;
  left: 5%;
  right: 5%;
  bottom: 5%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 20;
}
_x000D_
<div id="logWindow">
  <pre id="logger"></pre>
</div>
_x000D_
_x000D_
_x000D_

Thanks this answer too, JSON.stringify() didn't work for this.

In Python, when to use a Dictionary, List or Set?

For C++ I was always having this flow chart in mind: In which scenario do I use a particular STL container?, so I was curious if something similar is available for Python3 as well, but I had no luck.

What you need to keep in mind for Python is: There is no single Python standard as for C++. Hence there might be huge differences for different Python interpreters (e.g. CPython, PyPy). The following flow chart is for CPython.

Additionally I found no good way to incorporate the following data structures into the diagram: bytes, byte arrays, tuples, named_tuples, ChainMap, Counter, and arrays.

  • OrderedDict and deque are available via collections module.
  • heapq is available from the heapq module
  • LifoQueue, Queue, and PriorityQueue are available via the queue module which is designed for concurrent (threads) access. (There is also a multiprocessing.Queue available but I don't know the differences to queue.Queue but would assume that it should be used when concurrent access from processes is needed.)
  • dict, set, frozen_set, and list are builtin of course

For anyone I would be grateful if you could improve this answer and provide a better diagram in every aspect. Feel free and welcome. flowchart

PS: the diagram has been made with yed. The graphml file is here

C# Public Enums in Classes

Just declare the enum outside the bounds of the class. Like this:

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
    ...
}

Remember that an enum is a type. You might also consider putting the enum in its own file if it's going to be used by other classes. (You're programming a card game and the suit is a very important attribute of the card that, in well-structured code, will need to be accessible by a number of classes.)

How do you handle a "cannot instantiate abstract class" error in C++?

If anyone is getting this error from a function, try using a reference to the abstract class in the parameters instead.

void something(Abstract bruh){
}

to

void something(Abstract& bruh){
}

Get top 1 row of each group

I just learned how to use cross apply. Here's how to use it in this scenario:

 select d.DocumentID, ds.Status, ds.DateCreated 
 from Documents as d 
 cross apply 
     (select top 1 Status, DateCreated
      from DocumentStatusLogs 
      where DocumentID = d.DocumentId
      order by DateCreated desc) as ds

How to write a test which expects an Error to be thrown in Jasmine?

As mentioned previously, a function needs to be passed to toThrow as it is the function you're describing in your test: "I expect this function to throw x"

expect(() => parser.parse(raw))
  .toThrow(new Error('Parsing is not possible'));

If using Jasmine-Matchers you can also use one of the following when they suit the situation;

// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
  .toThrowAnyError();

or

// I just want to know that an error of 
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
  .toThrowErrorOfType(TypeError);

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Check if a variable is between two numbers with Java

are you writing java code for android? in that case you should write maybe

if (90 >= angle && angle <= 180) {

updating the code to a nicer style (like some suggested) you would get:

if (angle <= 90 && angle <= 180) {

now you see that the second check is unnecessary or maybe you mixed up < and > signs in the first check and wanted actually to have

if (angle >= 90 && angle <= 180) {

How do I escape a reserved word in Oracle?

Oracle normally requires double-quotes to delimit the name of identifiers in SQL statements, e.g.

SELECT "MyColumn" AS "MyColAlias"
FROM "MyTable" "Alias"
WHERE "ThisCol" = 'That Value';

However, it graciously allows omitting the double-quotes, in which case it quietly converts the identifier to uppercase:

SELECT MyColumn AS MyColAlias
FROM MyTable Alias
WHERE ThisCol = 'That Value';

gets internally converted to something like:

SELECT "ALIAS" . "MYCOLUMN" AS "MYCOLALIAS"
FROM "THEUSER" . "MYTABLE" "ALIAS"
WHERE "ALIAS" . "THISCOL" = 'That Value';

Change hash without reload in jQuery

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});

Managing large binary files with Git

I am looking for opinions of how to handle large binary files on which my source code (web application) is dependent. What are your experiences/thoughts regarding this?

I personally have run into synchronisation failures with Git with some of my cloud hosts once my web applications binary data notched above the 3 GB mark. I considered BFT Repo Cleaner at the time, but it felt like a hack. Since then I've begun to just keep files outside of Git purview, instead leveraging purpose-built tools such as Amazon S3 for managing files, versioning and back-up.

Does anybody have experience with multiple Git repositories and managing them in one project?

Yes. Hugo themes are primarily managed this way. It's a little kudgy, but it gets the job done.


My suggestion is to choose the right tool for the job. If it's for a company and you're managing your codeline on GitHub pay the money and use Git-LFS. Otherwise you could explore more creative options such as decentralized, encrypted file storage using blockchain.

Additional options to consider include Minio and s3cmd.

Send data from javascript to a mysql database

JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.

JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.

Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:

http://www.w3schools.com/php/php_ajax_database.asp

And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.

In particular, pay attention to these bits of code from that article.

Bits of Javascript:

xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();

Bits of PHP code:

mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);

Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.

The code from the article

HTML/Javascript code:

<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

PHP code:

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

py2exe - generate single executable file

I'm told bbfreeze will create a single file .EXE, and is newer than py2exe.

How to store a dataframe using Pandas

Pandas DataFrames have the to_pickle function which is useful for saving a DataFrame:

import pandas as pd

a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

a.to_pickle('my_file.pkl')

b = pd.read_pickle('my_file.pkl')
print b
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

MVC 4 Edit modal form using Bootstrap

In reply to Dimitrys answer but using Ajax.BeginForm the following works at least with MVC >5 (4 not tested).

  1. write a model as shown in the other answers,

  2. In the "parent view" you will probably use a table to show the data. Model should be an ienumerable. I assume, the model has an id-property. Howeverm below the template, a placeholder for the modal and corresponding javascript

    <table>
    @foreach (var item in Model)
    {
        <tr> <td id="[email protected]"> 
            @Html.Partial("dataRowView", item)
        </td> </tr>
    }
    </table>
    
    <div class="modal fade" id="editor-container" tabindex="-1" 
         role="dialog" aria-labelledby="editor-title">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" id="editor-content-container"></div>
        </div>
    </div> 
    
    <script type="text/javascript">
        $(function () {
            $('.editor-container').click(function () {
                var url = "/area/controller/MyEditAction";  
                var id = $(this).attr('data-id');  
                $.get(url + '/' + id, function (data) {
                    $('#editor-content-container').html(data);
                    $('#editor-container').modal('show');
                });
            });
        });
    
        function success(data,status,xhr) {
            $('#editor-container').modal('hide');
            $('#editor-content-container').html("");
        }
    
        function failure(xhr,status,error) {
            $('#editor-content-container').html(xhr.responseText);
            $('#editor-container').modal('show');
        }
    </script>
    

note the "editor-success-id" in data table rows.

  1. The dataRowView is a partial containing the presentation of an model's item.

    @model ModelView
    @{
        var item = Model;
    }
    <div class="row">
            // some data 
            <button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
    </div>
    
  2. Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ... ).

    @model Model
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="editor-title">Title</h4>
    </div>
    @using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
                        new AjaxOptions
                        {
                            InsertionMode = InsertionMode.Replace,
                            HttpMethod = "POST",
                            UpdateTargetId = "editor-success-" + @Model.Id,
                            OnSuccess = "success",
                            OnFailure = "failure",
                        }))
    {
        @Html.ValidationSummary()
        @Html.AntiForgeryToken()
        @Html.HiddenFor(model => model.Id)
        <div class="modal-body">
            <div class="form-horizontal">
                // Models input fields
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    }
    

This is where magic happens: in AjaxOptions, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.

This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.

But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:

  1. the corresponding controller action method for the partial edit modal

    [HttpGet]
    public async Task<ActionResult> EditPartData(Guid? id)
    {
        // Find the data row and return the edit form
        Model input = await db.Models.FindAsync(id);
        return PartialView("EditModel", input);
    }
    
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> MyEditAction([Bind(Include =
       "Id,Fields,...")] ModelView input)
    {
        if (TryValidateModel(input))
        {  
            // save changes, return new data row  
            // status code is something in 200-range
            db.Entry(input).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return PartialView("dataRowView", (ModelView)input);
        }
    
        // set the "error status code" that will redisplay the modal
        Response.StatusCode = 400;
        // and return the edit form, that will be displayed as a 
        // modal again - including the modelstate errors!
        return PartialView("EditModel", (Model)input);
    }
    

This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.

Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js (may be installed by NuGet):

        bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
                    "~/Scripts/jquery.unobtrusive-ajax.js"));

Arduino Tools > Serial Port greyed out

Same comment as Philip Kirkbride. It wasn't a permission issue, but using the Arduino IDE downloaded from their website solved my problem. Thanks! Michael

jQuery: how to get which button was clicked upon form submission?

A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':

$("button").click(function() {
  var id = $(this).attr('id');
  ... 
});

MySQL Results as comma separated list

You can use GROUP_CONCAT to perform that, e.g. something like

SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;

How to remove part of a string?

If you want to remove part of string

let str = "test_23";
str.replace("test_", "");
// 23

If you want to replace part of string

let str = "test_23";
str.replace("test_", "student-");
// student-23

How to display hexadecimal numbers in C?

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

int to string in MySQL

You can do this:

select t2.*
from t1
join t2 on t2.url = 'site.com/path/' + CAST(t1.id AS VARCHAR(10)) + '/more' 
where t1.id > 9000

Pay attention to CAST(t1.id AS VARCHAR(10)).

PHP function to make slug (URL string)

Don't use preg_replace for this. There's a php function built just for the task: strtr() http://php.net/manual/en/function.strtr.php

Taken from the comments in the above link (and I tested it myself; it works:

function normalize ($string) {
    $table = array(
        'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'd'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
        'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
        'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
        'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
        'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
        'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
        'ÿ'=>'y', 'R'=>'R', 'r'=>'r',
    );

    return strtr($string, $table);
}

How to hide columns in HTML table?

Bootstrap people use .hidden class on <td>.

Adding CSRFToken to Ajax request

The answer above didn't work for me.

I added the following code before my ajax request:

function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
            var csrftoken = getCookie('csrftoken');

            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }

            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                     type: 'POST',
                     url: '/url/',
            });

How do I get the current date and current time only respectively in Django?

import datetime

datetime.date.today()  # Returns 2018-01-15

datetime.datetime.now() # Returns 2018-01-15 09:00

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

Removing highcharts.com credits link

add

credits: {
    enabled: false
}

[NOTE] that it is in the same line with xAxis: {} and yAxis: {}

FlutterError: Unable to load asset

I was also facing the same issue . The issue on my side was that the image name was having the space in between its name so I updated the image name with the new name that does not have any space.

Image name creating the error was comboclr emtpy no circle.png

I updated this name to comboclr_emtpy_no_circle.png

Most useful NLog configurations

Log from Silverlight

When using NLog with Silverlight you can send the trace to the server side via the provided web service. You can also write to a local file in the Isolated Storage, which come in handy if the web server is unavailable. See here for details, i.e. use something like this to make yourself a target:

namespace NLogTargets
{
    [Target("IsolatedStorageTarget")]
    public sealed class IsolatedStorageTarget : TargetWithLayout
    {
        IsolatedStorageFile _storageFile = null;
        string _fileName = "Nlog.log"; // Default. Configurable through the 'filename' attribute in nlog.config

        public IsolatedStorageTarget()
        {
        }

        ~IsolatedStorageTarget()
        {
            if (_storageFile != null)
            {
                _storageFile.Dispose();
                _storageFile = null;
            }
        }

        public string filename
        {
            set
            {
                _fileName = value; 
            }
            get
            {
                return _fileName;  
            }
         }

        protected override void Write(LogEventInfo logEvent)
        {
            try
            {
                writeToIsolatedStorage(this.Layout.Render(logEvent));
            }
            catch (Exception e)
            {
                // Not much to do about his....
            }
        }

        public void writeToIsolatedStorage(string msg)
        {
            if (_storageFile == null)
                _storageFile = IsolatedStorageFile.GetUserStoreForApplication();
            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // The isolated storage is limited in size. So, when approaching the limit
                // simply purge the log file. (Yeah yeah, the file should be circular, I know...)
                if (_storageFile.AvailableFreeSpace < msg.Length * 100)
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Truncate, FileAccess.Write, isolatedStorage))
                    { }
                }
                // Write to isolated storage
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, FileMode.Append, FileAccess.Write, isolatedStorage))
                {
                    using (TextWriter writer = new StreamWriter(stream))
                    {
                        writer.WriteLine(msg);
                    }
                }
            }
        }
    } 
}

View stored procedure/function definition in MySQL

something like:

DELIMITER //

CREATE PROCEDURE alluser()
BEGIN
   SELECT *
   FROM users;
END //

DELIMITER ;

than:

SHOW CREATE PROCEDURE alluser

gives result:

'alluser', 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER', 'CREATE DEFINER=`root`@`localhost` PROCEDURE `alluser`()
BEGIN
   SELECT *
   FROM users;
END'

How to change the author and committer name and e-mail of multiple commits in Git?

If you want to (easily) change the author for the current branch I would use something like this:

# update author for everything since origin/master
git rebase \
  -i origin/master \
  --exec 'git commit --amend --no-edit --author="Author Name <[email protected]>"'

How to initialize a vector with fixed length in R

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

HTML Agility pack - parsing tables

In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:

    List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
                                       from row in table?.SelectNodes(HtmlBody.TR)
                                       let rows = row.SelectSingleNode(HtmlBody.TR)
                                       where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
                                       select new TableRow
                                       {
                                           Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
                                           Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
                                       }  

TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:

_x000D_
_x000D_
<tr>_x000D_
    <td width="28%">&nbsp;</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.

The project description file (.project) for my project is missing

In my case i have changed the root folder in which the Eclipse project were stored. I have discovered tha when i have runned :

cat .plugins/org.eclip.resources/.projects/<projectname>/.location 

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

How to redirect a URL path in IIS?

Format the redirect URL in the following way:

stuff.mysite.org.uk$S$Q

The $S will say that any path must be applied to the new URL. $Q says that any parameter variables must be passed to the new URL.

In IIS 7.0, you must enable the option Redirect to exact destination. I believe there must be an option like this in IIS 6.0 too.

Linking dll in Visual Studio

You don't add or link directly against a DLL, you link against the LIB produced by the DLL.

A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).

To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:

#pragma comment(lib, "dll.lib")

With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

I've seen several answers and that's the only procedure that let me fix that without any conflicts.

If you want all changes from branch_new in branch_old, then:

git checkout branch_new
git merge -s ours branch_old
git checkout branch_old
git merge branch_new

once applied those four commands you can push the branch_old without any problem

VBA - Range.Row.Count

This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k accordingly (k - 1) if you have a header row for filtering:

k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count

Decimal values in SQL for dividing results

There may be other ways to get your desired result.

Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)

Remove Rows From Data Frame where a Row matches a String

You can use the dplyr package to easily remove those particular rows.

library(dplyr)
df <- filter(df, C != "Foo")

how to generate a unique token which expires after 24 hours?

you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.

To generate key refer here

RS256 vs HS256: What's the difference?

There is a difference in performance.

Simply put HS256 is about 1 order of magnitude faster than RS256 for verification but about 2 orders of magnitude faster than RS256 for issuing (signing).

 640,251  91,464.3 ops/s
  86,123  12,303.3 ops/s (RS256 verify)
   7,046   1,006.5 ops/s (RS256 sign)

Don't get hung up on the actual numbers, just think of them with respect of each other.

[Program.cs]

class Program
{
    static void Main(string[] args)
    {
        foreach (var duration in new[] { 1, 3, 5, 7 })
        {
            var t = TimeSpan.FromSeconds(duration);

            byte[] publicKey, privateKey;

            using (var rsa = new RSACryptoServiceProvider())
            {
                publicKey = rsa.ExportCspBlob(false);
                privateKey = rsa.ExportCspBlob(true);
            }

            byte[] key = new byte[64];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
            }

            var s1 = new Stopwatch();
            var n1 = 0;

            using (var hs256 = new HMACSHA256(key))
            {
                while (s1.Elapsed < t)
                {
                    s1.Start();
                    var hash = hs256.ComputeHash(privateKey);
                    s1.Stop();
                    n1++;
                }
            }

            byte[] sign;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                sign = rsa.SignData(privateKey, "SHA256");
            }

            var s2 = new Stopwatch();
            var n2 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(publicKey);

                while (s2.Elapsed < t)
                {
                    s2.Start();
                    var success = rsa.VerifyData(privateKey, "SHA256", sign);
                    s2.Stop();
                    n2++;
                }
            }

            var s3 = new Stopwatch();
            var n3 = 0;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(privateKey);

                while (s3.Elapsed < t)
                {
                    s3.Start();
                    rsa.SignData(privateKey, "SHA256");
                    s3.Stop();
                    n3++;
                }
            }

            Console.WriteLine($"{s1.Elapsed.TotalSeconds:0} {n1,7:N0} {n1 / s1.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s2.Elapsed.TotalSeconds:0} {n2,7:N0} {n2 / s2.Elapsed.TotalSeconds,9:N1} ops/s");
            Console.WriteLine($"{s3.Elapsed.TotalSeconds:0} {n3,7:N0} {n3 / s3.Elapsed.TotalSeconds,9:N1} ops/s");

            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n2 / s2.Elapsed.TotalSeconds),9:N1}x slower (verify)");
            Console.WriteLine($"RS256 is {(n1 / s1.Elapsed.TotalSeconds) / (n3 / s3.Elapsed.TotalSeconds),9:N1}x slower (issue)");

            // RS256 is about 7.5x slower, but it can still do over 10K ops per sec.
        }
    }
}

Subversion stuck due to "previous operation has not finished"?

I've been in similar situations. Have you tried running cleanup from the root of your workspace? I know sometimes a cleanup from a child directory (where the problem lies) doesn't work, and cleanup from the root of the workspace does.

If that still fails, since you had deleted a child dir somewhere. Try deleting 1 level higher from the child dir as well (assuming that is not the root), and re-trying update and cleanup.

If cleanup attempts aren't succeeding at any level then the answer is unfortunately checkout a new working copy.

Event detect when css property changed using Jquery

You can use jQuery's css function to test the CSS properties, eg. if ($('node').css('display') == 'block').

Colin is right, that there is no explicit event that gets fired when a specific CSS property gets changed. But you may be able to flip it around, and trigger an event that sets the display, and whatever else.

Also consider using adding CSS classes to get the behavior you want. Often you can add a class to a containing element, and use CSS to affect all elements. I often slap a class onto the body element to indicate that an AJAX response is pending. Then I can use CSS selectors to get the display I want.

Not sure if this is what you're looking for.

CSS3 Box Shadow on Top, Left, and Right Only

#div:before {
 content:"";
 position:absolute;
 width:100%;
 background:#fff;
 height:38px;
 top:1px;
 right:-5px;
}

How to trigger event when a variable's value is changed?

You can use a property setter to raise an event whenever the value of a field is going to change.

You can have your own EventHandler delegate or you can use the famous System.EventHandler delegate.

Usually there's a pattern for this:

  1. Define a public event with an event handler delegate (that has an argument of type EventArgs).
  2. Define a protected virtual method called OnXXXXX (OnMyPropertyValueChanged for example). In this method you should check if the event handler delegate is null and if not you can call it (it means that there are one or more methods attached to the event delegation).
  3. Call this protected method whenever you want to notify subscribers that something has changed.

Here's an example

private int _age;

//#1
public event System.EventHandler AgeChanged;

//#2
protected virtual void OnAgeChanged()
{ 
     if (AgeChanged != null) AgeChanged(this,EventArgs.Empty); 
}

public int Age
{
    get
    {
         return _age;
    }

    set
    {
         //#3
         _age=value;
         OnAgeChanged();
    }
 }

The advantage of this approach is that you let any other classes that want to inherit from your class to change the behavior if necessary.

If you want to catch an event in a different thread that it's being raised you must be careful not to change the state of objects that are defined in another thread which will cause a cross thread exception to be thrown. To avoid this you can either use an Invoke method on the object that you want to change its state to make sure that the change is happening in the same thread that the event has been raised or in case that you are dealing with a Windows Form you can use a BackgourndWorker to do things in a parallel thread nice and easy.

HTML5 Video Autoplay not working correctly

Try autoplay="autoplay" instead of the "true" value. That's the documented way to enable autoplay. That sounds weirdly redundant, I know.

Scanner vs. StringTokenizer vs. String.Split

String.split() works very good but has its own boundaries, like if you wanted to split a string as shown below based on single or double pipe (|) symbol, it doesn't work. In this situation you can use StringTokenizer.

ABC|IJK

Overriding fields or properties in subclasses

If you are building a class and you want there to be a base value for the property, then use the virtual keyword in the base class. This allows you to optionally override the property.

Using your example above:

//you may want to also use interfaces.
interface IFather
{
    int MyInt { get; set; }
}


public class Father : IFather
{
    //defaulting the value of this property to 1
    private int myInt = 1;

    public virtual int MyInt
    {
        get { return myInt; }
        set { myInt = value; }
    }
}

public class Son : Father
{
    public override int MyInt
    {
        get {

            //demonstrating that you can access base.properties
            //this will return 1 from the base class
            int baseInt = base.MyInt;

            //add 1 and return new value
            return baseInt + 1;
        }
        set
        {
            //sets the value of the property
            base.MyInt = value;
        }
    }
}

In a program:

Son son = new Son();
//son.MyInt will equal 2

How to convert Set to Array?

Here is an easy way to get only unique raw values from array. If you convert the array to Set and after this, do the conversion from Set to array. This conversion works only for raw values, for objects in the array it is not valid. Try it by yourself.

    let myObj1 = {
        name: "Dany",
        age: 35,
        address: "str. My street N5"
    }

    let myObj2 = {
        name: "Dany",
        age: 35,
        address: "str. My street N5"
    }

    var myArray = [55, 44, 65, myObj1, 44, myObj2, 15, 25, 65, 30];
    console.log(myArray);

    var mySet = new Set(myArray);
    console.log(mySet);

    console.log(mySet.size === myArray.length);// !! The size differs because Set has only unique items

    let uniqueArray = [...mySet];
    console.log(uniqueArray); 
    // Here you will see your new array have only unique elements with raw 
    // values. The objects are not filtered as unique values by Set.
    // Try it by yourself.

Validate date in dd/mm/yyyy format using JQuery Validate

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

Need to list all triggers in SQL Server database with table name and table's schema

And what do you think about this: Very short and neat :)

SELECT OBJECT_NAME(parent_id) Table_or_ViewNM,
      name TriggerNM,
      is_instead_of_trigger,
      is_disabled
FROM sys.triggers
WHERE parent_class_desc = 'OBJECT_OR_COLUMN'
ORDER BY OBJECT_NAME(parent_id),
Name ;

Can I write or modify data on an RFID tag?

It depends on the type of chip you are using, but nowerdays most chips you can write. It also depends on how much power you give your RFID device. To read you dont need allot of power and very little line of sight. To right you need them full insight and longer insight

Assign JavaScript variable to Java Variable in JSP

You need to read something about a JSP's lifecycle. Try this: http://en.wikipedia.org/wiki/File:JSPLife.png

JavaScript runs on the client, but in order to change the jsp, you need access to the server. This can be done through Ajax(http://en.wikipedia.org/wiki/Ajax_%28programming%29).

Here are some Ajax-related links: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

Using ls to list directories and their total sizes

just a warning, if you want to compare sizes of files. du produces different results depending on file system, block size, ... .

It may happen that the size of the files is different, e.g. comparing the same directory on your local hard-disk and a USB mass storage device. I use the following script, including ls to sum up the directory size. The result in in bytes taking all sub directories into account.

echo "[GetFileSize.sh] target directory: \"$1\""

iRetValue=0

uiLength=$(expr length "$1")
if [ $uiLength -lt 2 ]; then
  echo "[GetFileSize.sh] invalid target directory: \"$1\" - exiting!"
  iRetValue=-1
else
  echo "[GetFileSize.sh] computing size of files..."

  # use ls to compute total size of all files - skip directories as they may
  # show different sizes, depending on block size of target disk / file system
  uiTotalSize=$(ls -l -R $1 | grep -v ^d | awk '{total+=$5;} END {print total;}')
  uiLength=$(expr length "$uiTotalSize")
  if [ $uiLength -lt 1 ]; then
    uiTotalSize=0
  fi
  echo -e "[GetFileSize.sh] total target file size: \"$uiTotalSize\""

fi

exit "$iRetValue"

"No X11 DISPLAY variable" - what does it mean?

Are you running this from within an X11 environment? You can use a terminal window, but it has to be within X (either after a graphical login, or by running startx).

If you're already within a graphical environment, try export DISPLAY=:0 for bash like shells (bash, sh, etc) or setenv DISPLAY :0 for C shell based shells (csh, tcsh, etc)

If you've connected from another machine via SSH, you use the -X option to display the graphical interface on the machine you're sitting at (provided there's an X server running there (such as xming for windows, and your standard Linux X server).

Rails 4: how to use $(document).ready() with turbo-links

Here's what I do... CoffeeScript:

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

last line listens for page load which is what turbo links will trigger.

Edit...adding Javascript version (per request):

var ready;
ready = function() {

  ...your javascript goes here...

};

$(document).ready(ready);
$(document).on('page:load', ready);

Edit 2...For Rails 5 (Turbolinks 5) page:load becomes turbolinks:load and will be even fired on initial load. So we can just do the following:

$(document).on('turbolinks:load', function() {

  ...your javascript goes here...

});

PHP Curl UTF-8 Charset

function page_title($val){
    include(dirname(__FILE__).'/simple_html_dom.php');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$val);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
    curl_setopt($ch, CURLOPT_ENCODING , "gzip");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $return = curl_exec($ch); 
    $encot = false;
    $charset = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

    curl_close($ch); 
    $html = str_get_html('"'.$return.'"');

    if(strpos($charset,'charset=') !== false) {
        $c = str_replace("text/html; charset=","",$charset);
        $encot = true;
    }
    else {
        $lookat=$html->find('meta[http-equiv=Content-Type]',0);
        $chrst = $lookat->content;
        preg_match('/charset=(.+)/', $chrst, $found);
        $p = trim($found[1]);
        if(!empty($p) && $p != "")
        {
            $c = $p;
            $encot = true;
        }
    }
    $title = $html->find('title')[0]->innertext;
    if($encot == true && $c != 'utf-8' && $c != 'UTF-8') $title = mb_convert_encoding($title,'UTF-8',$c);

    return $title;
}

Adding a Method to an Existing Object Instance

This question was opened years ago, but hey, there's an easy way to simulate the binding of a function to a class instance using decorators:

def binder (function, instance):
  copy_of_function = type (function) (function.func_code, {})
  copy_of_function.__bind_to__ = instance
  def bound_function (*args, **kwargs):
    return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs)
  return bound_function


class SupaClass (object):
  def __init__ (self):
    self.supaAttribute = 42


def new_method (self):
  print self.supaAttribute


supaInstance = SupaClass ()
supaInstance.supMethod = binder (new_method, supaInstance)

otherInstance = SupaClass ()
otherInstance.supaAttribute = 72
otherInstance.supMethod = binder (new_method, otherInstance)

otherInstance.supMethod ()
supaInstance.supMethod ()

There, when you pass the function and the instance to the binder decorator, it will create a new function, with the same code object as the first one. Then, the given instance of the class is stored in an attribute of the newly created function. The decorator return a (third) function calling automatically the copied function, giving the instance as the first parameter.

In conclusion you get a function simulating it's binding to the class instance. Letting the original function unchanged.

Avoid browser popup blockers

Based on Jason Sebring's very useful tip, and on the stuff covered here and there, I found a perfect solution for my case:

Pseudo code with Javascript snippets:

  1. immediately create a blank popup on user action

     var importantStuff = window.open('', '_blank');
    

    (Enrich the call to window.open with whatever additional options you need.)

    Optional: add some "waiting" info message. Examples:

    a) An external HTML page: replace the above line with

     var importantStuff = window.open('http://example.com/waiting.html', '_blank');
    

    b) Text: add the following line below the above one:

     importantStuff.document.write('Loading preview...');
    
  2. fill it with content when ready (when the AJAX call is returned, for instance)

     importantStuff.location.href = 'https://example.com/finally.html';
    

    Alternatively, you could close the window here if you don't need it after all (if ajax request fails, for example - thanks to @Goose for the comment):

     importantStuff.close();
    

I actually use this solution for a mailto redirection, and it works on all my browsers (windows 7, Android). The _blank bit helps for the mailto redirection to work on mobile, btw.

How to get rid of blank pages in PDF exported from SSRS

If the pages are blank coming from SSRS, you need to tweak your report layout. This will be far more efficient than running the output through and post process to repair the side effects of a layout problem.

SSRS is very finicky when it comes to pushing the boundaries of the margins. It is easy to accidentally widen/lengthen the report just by adjusting text box or other control on the report. Check the width and height property of the report surface carefully and squeeze them as much as possible. Watch out for large headers and footers.

Ant build failed: "Target "build..xml" does not exist"

  1. Probably you don't have environment variable ANT_HOME set properly
  2. It seems that you are calling Ant like this: "ant build..xml". If your ant script has name build.xml you need to specify only a target in command line. For example: "ant target1".

How to use Select2 with JSON via Ajax request?

for select2 v4.0.0 slightly different

$(".itemSearch").select2({
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    ajax: {
        url: URL,
        dataType: "json",
        type: "GET",
        data: function (params) {

            var queryParameters = {
                term: params.term
            }
            return queryParameters;
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    }
});

Full Page <iframe>

Put this in your CSS.

iframe {
  width: 100%;
  height: 100vh;
}

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

Git push existing repo to a new and different remote repo server?

There is a deleted answer on this question that had a useful link: https://help.github.com/articles/duplicating-a-repository

The gist is

0. create the new empty repository (say, on github)
1. make a bare clone of the repository in some temporary location
2. change to the temporary location
3. perform a mirror-push to the new repository
4. change to another location and delete the temporary location

OP's example:

On your local machine

$ cd $HOME
$ git clone --bare https://git.fedorahosted.org/the/path/to/my_repo.git
$ cd my_repo.git
$ git push --mirror https://github.com/my_username/my_repo.git
$ cd ..
$ rm -rf my_repo.git

Instantly detect client disconnection from server socket

Implementing heartbeat into your system might be a solution. This is only possible if both client and server are under your control. You can have a DateTime object keeping track of the time when the last bytes were received from the socket. And assume that the socket not responded over a certain interval are lost. This will only work if you have heartbeat/custom keep alive implemented.

How do I call a function twice or more times consecutively?

You could define a function that repeats the passed function N times.

def repeat_fun(times, f):
    for i in range(times): f()

If you want to make it even more flexible, you can even pass arguments to the function being repeated:

def repeat_fun(times, f, *args):
    for i in range(times): f(*args)

Usage:

>>> def do():
...   print 'Doing'
... 
>>> def say(s):
...   print s
... 
>>> repeat_fun(3, do)
Doing
Doing
Doing
>>> repeat_fun(4, say, 'Hello!')
Hello!
Hello!
Hello!
Hello!

YYYY-MM-DD format date in shell script

You can do something like this:

$ date +'%Y-%m-%d'

How do I edit SSIS package files?

If you use the 'Export Data' wizard there is an option to store the configuration as an 'Integration Services Projects' within the SQL Server database . To edit this package follow the instructions from "mikeTheLiar" but instead of searching for a file make a connection to the database and export package.

From "mikeTheLiar": File->New Project->Integration Services Project - Now in solution explorer there is a SSIS Packages folder, right click it and select "Add Existing Package".

Using the default dialog make a connection to the database and open the export package. The package can now be edited.

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

React - How to pass HTML tags in props?

<MyComponent text={<span>This is <strong>not</strong> working.</span>} />

and then in your component you can do prop checking like so:

import React from 'react';
export default class MyComponent extends React.Component {
  static get propTypes() {
    return {
      text: React.PropTypes.object, // if you always want react components
      text: React.PropTypes.any, // if you want both text or react components
    }
  }
}

Make sure you choose only one prop type.

json call with C#

Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):

public static bool SendAnSMSMessage(string message)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
    httpWebRequest.ContentType = "text/json";
    httpWebRequest.Method = "POST";

    var serializer = new Newtonsoft.Json.JsonSerializer();
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
        {
             serializer.Serialize(tw, 
                 new {method= "send",
                      @params = new string[]{
                          "IPutAGuidHere", 
                          "[email protected]",
                          "MyTenDigitNumberWasHere",
                          message
                      }});
        }
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        //Now you have your response.
        //or false depending on information in the response
        return true;        
    }
}

hexadecimal string to byte array in python

You should be able to build a string holding the binary data using something like:

data = "fef0babe"
bits = ""
for x in xrange(0, len(data), 2)
  bits += chr(int(data[x:x+2], 16))

This is probably not the fastest way (many string appends), but quite simple using only core Python.

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

How to properly create composite primary keys - MYSQL

CREATE  TABLE `mom`.`sec_subsection` (

  `idsec_sub` INT(11) NOT NULL ,

  `idSubSections` INT(11) NOT NULL ,

  PRIMARY KEY (`idsec_sub`, `idSubSections`) 

);

How can I debug a .BAT script?

Did you try to reroute the result to a file? Like whatever.bat >log.txt

You have to make sure that in this case every other called script is also logging to the file like >>log.txt

Also if you put a date /T and time /T in the beginning and in the end of that batch file, you will get the times it was at that point and you can map your script running time and order.

ASP.NET MVC3 - textarea with @Html.EditorFor

Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:

@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })

That works for me. The '@' is used to escape keywords so they are treated as variables/properties.

What is a bus error?

You can also get SIGBUS when a code page cannot be paged in for some reason.

Is there a label/goto in Python?

I was looking for some thing similar to

for a in xrange(1,10):
A_LOOP
    for b in xrange(1,5):
        for c in xrange(1,5):
            for d in xrange(1,5):
                # do some stuff
                if(condition(e)):
                    goto B_LOOP;

So my approach was to use a boolean to help breaking out from the nested for loops:

for a in xrange(1,10):
    get_out = False
    for b in xrange(1,5):
        if(get_out): break
        for c in xrange(1,5):
            if(get_out): break
            for d in xrange(1,5):
                # do some stuff
                if(condition(e)):
                    get_out = True
                    break

How to replace multiple white spaces with one white space

This question isn't as simple as other posters have made it out to be (and as I originally believed it to be) - because the question isn't quite precise as it needs to be.

There's a difference between "space" and "whitespace". If you only mean spaces, then you should use a regex of " {2,}". If you mean any whitespace, that's a different matter. Should all whitespace be converted to spaces? What should happen to space at the start and end?

For the benchmark below, I've assumed that you only care about spaces, and you don't want to do anything to single spaces, even at the start and end.

Note that correctness is almost always more important than performance. The fact that the Split/Join solution removes any leading/trailing whitespace (even just single spaces) is incorrect as far as your specified requirements (which may be incomplete, of course).

The benchmark uses MiniBench.

using System;
using System.Text.RegularExpressions;
using MiniBench;

internal class Program
{
    public static void Main(string[] args)
    {

        int size = int.Parse(args[0]);
        int gapBetweenExtraSpaces = int.Parse(args[1]);

        char[] chars = new char[size];
        for (int i=0; i < size/2; i += 2)
        {
            // Make sure there actually *is* something to do
            chars[i*2] = (i % gapBetweenExtraSpaces == 1) ? ' ' : 'x';
            chars[i*2 + 1] = ' ';
        }
        // Just to make sure we don't have a \0 at the end
        // for odd sizes
        chars[chars.Length-1] = 'y';

        string bigString = new string(chars);
        // Assume that one form works :)
        string normalized = NormalizeWithSplitAndJoin(bigString);


        var suite = new TestSuite<string, string>("Normalize")
            .Plus(NormalizeWithSplitAndJoin)
            .Plus(NormalizeWithRegex)
            .RunTests(bigString, normalized);

        suite.Display(ResultColumns.All, suite.FindBest());
    }

    private static readonly Regex MultipleSpaces = 
        new Regex(@" {2,}", RegexOptions.Compiled);

    static string NormalizeWithRegex(string input)
    {
        return MultipleSpaces.Replace(input, " ");
    }

    // Guessing as the post doesn't specify what to use
    private static readonly char[] Whitespace =
        new char[] { ' ' };

    static string NormalizeWithSplitAndJoin(string input)
    {
        string[] split = input.Split
            (Whitespace, StringSplitOptions.RemoveEmptyEntries);
        return string.Join(" ", split);
    }
}

A few test runs:

c:\Users\Jon\Test>test 1000 50
============ Normalize ============
NormalizeWithSplitAndJoin  1159091 0:30.258 22.93
NormalizeWithRegex        26378882 0:30.025  1.00

c:\Users\Jon\Test>test 1000 5
============ Normalize ============
NormalizeWithSplitAndJoin  947540 0:30.013 1.07
NormalizeWithRegex        1003862 0:29.610 1.00


c:\Users\Jon\Test>test 1000 1001
============ Normalize ============
NormalizeWithSplitAndJoin  1156299 0:29.898 21.99
NormalizeWithRegex        23243802 0:27.335  1.00

Here the first number is the number of iterations, the second is the time taken, and the third is a scaled score with 1.0 being the best.

That shows that in at least some cases (including this one) a regular expression can outperform the Split/Join solution, sometimes by a very significant margin.

However, if you change to an "all whitespace" requirement, then Split/Join does appear to win. As is so often the case, the devil is in the detail...

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

Apart of larsmans answer (who is indeed correct), the exception in a call to a get() method, so the code you have posted is not the one that is causing the error.

How to convert an IPv4 address into a integer in C#?

public bool TryParseIPv4Address(string value, out uint result)
{
    IPAddress ipAddress;

    if (!IPAddress.TryParse(value, out ipAddress) ||
        (ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork))
    {
        result = 0;
        return false;
    }

    result = BitConverter.ToUInt32(ipAddress.GetAddressBytes().Reverse().ToArray(), 0);
    return true;
}

How to get all possible combinations of a list’s elements?

Below is a "standard recursive answer", similar to the other similar answer https://stackoverflow.com/a/23743696/711085 . (We don't realistically have to worry about running out of stack space since there's no way we could process all N! permutations.)

It visits every element in turn, and either takes it or leaves it (we can directly see the 2^N cardinality from this algorithm).

def combs(xs, i=0):
    if i==len(xs):
        yield ()
        return
    for c in combs(xs,i+1):
        yield c
        yield c+(xs[i],)

Demo:

>>> list( combs(range(5)) )
[(), (0,), (1,), (1, 0), (2,), (2, 0), (2, 1), (2, 1, 0), (3,), (3, 0), (3, 1), (3, 1, 0), (3, 2), (3, 2, 0), (3, 2, 1), (3, 2, 1, 0), (4,), (4, 0), (4, 1), (4, 1, 0), (4, 2), (4, 2, 0), (4, 2, 1), (4, 2, 1, 0), (4, 3), (4, 3, 0), (4, 3, 1), (4, 3, 1, 0), (4, 3, 2), (4, 3, 2, 0), (4, 3, 2, 1), (4, 3, 2, 1, 0)]

>>> list(sorted( combs(range(5)), key=len))
[(), 
 (0,), (1,), (2,), (3,), (4,), 
 (1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), 
 (2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1), (4, 1, 0), (4, 2, 0), (4, 2, 1), (4, 3, 0), (4, 3, 1), (4, 3, 2), 
 (3, 2, 1, 0), (4, 2, 1, 0), (4, 3, 1, 0), (4, 3, 2, 0), (4, 3, 2, 1), 
 (4, 3, 2, 1, 0)]

>>> len(set(combs(range(5))))
32

How to provide a mysql database connection in single file in nodejs

try this

var express = require('express');

var mysql     =    require('mysql');

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
console.log(app);
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "admin123",
  database: "sitepoint"
});

con.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});



module.exports = app;

iPhone UILabel text soft shadow

I tried almost all of these techniques (except FXLabel) and couldn't get any of them to work with iOS 7. I did eventually find THLabel which is working perfectly for me. I used THLabel in Interface Builder and setup User Defined Runtime Attributes so that it's easy for a non programmer to control the look and feel.

https://github.com/MuscleRumble/THLabel

ScrollIntoView() causing the whole page to move

Just to add an answer as per my latest experience and working on VueJs. I found below piece of code ad best, which does not impact your application in anyways.

const el = this.$el.getElementsByClassName('your_element_class')[0];
if (el) {
   scrollIntoView(el,
                  {
                       block: 'nearest',
                       inline: 'start',
                       behavior: 'smooth',
                       boundary: document.getElementsByClassName('main_app_class')[0]
                    });
     }

main_app_class is the root class

your_element_class is the element/view where you can to scroll into

And for browser which does not support ScrollIntoView() just use below library its awesome https://www.npmjs.com/package/scroll-into-view-if-needed

How to increase Bootstrap Modal Width?

In Bootstrap 3 you need to change the modal-dialog. So, in this case, you can add the class modal-admin in the place where modal-dialog stands.

@media (min-width: 768px) {
  .modal-dialog {
    width: 600;
    margin: 30px auto;
  }
  .modal-content {
    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
            box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
  }
  .modal-sm {
    width: 300px;
  }
}

How do I check if a cookie exists?

instead of the cookie variable you would just use document.cookie.split...

_x000D_
_x000D_
var cookie = 'cookie1=s; cookie1=; cookie2=test';_x000D_
var cookies = cookie.split('; ');_x000D_
cookies.forEach(function(c){_x000D_
  if(c.match(/cookie1=.+/))_x000D_
   console.log(true);_x000D_
});
_x000D_
_x000D_
_x000D_

Run java jar file on a server as background process

Systemd which now runs in the majority of distros

Step 1:

Find your user defined services mine was at /usr/lib/systemd/system/

Step 2:

Create a text file with your favorite text editor name it whatever_you_want.service

Step 3:

Put following Template to the file whatever_you_want.service

[Unit]
Description=webserver Daemon

[Service]
ExecStart=/usr/bin/java -jar /web/server.jar
User=user

[Install]
WantedBy=multi-user.target

Step 4:

Run your service
as super user

$ systemctl start whatever_you_want.service # starts the service
$ systemctl enable whatever_you_want.service # auto starts the service
$ systemctl disable whatever_you_want.service # stops autostart
$ systemctl stop whatever_you_want.service # stops the service
$ systemctl restart whatever_you_want.service # restarts the service

How to remove last n characters from every element in the R vector

Here's a way with gsub:

cs <- c("foo_bar","bar_foo","apple","beer")
gsub('.{3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"

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

  1. Click on the Network button
  2. Enable capture of network traffic by clicking on the green triangular button in top toolbar
  3. Capture some network traffic by interacting with the page
  4. Click on DETAILS/Cookies
  5. Step through each captured traffic segment; detailed information about cookies will be displayed

How can I call the 'base implementation' of an overridden virtual method?

You can do it, but not at the point you've specified. Within the context of B, you may invoke A.X() by calling base.X().

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

How to convert a char array back to a string?

String str = "wwwwww3333dfevvv";
char[] c = str.toCharArray();

Now to convert character array into String , there are two ways.

Arrays.toString(c);

Returns the string [w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v].

And:

String.valueOf(c)

Returns the string wwwwww3333dfevvv.

In Summary: pay attention to Arrays.toString(c), because you'll get "[w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v]" instead of "wwwwww3333dfevvv".

Difference between Key, Primary Key, Unique Key and Index in MySQL

Unique Keys: The columns in which no two rows are similar

Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.

Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.

Questions every good Database/SQL developer should be able to answer

What is the difference between a clustered index and a nonclustered index?

Another question I would ask that is not for a specific server would be:

What is a deadlock?

Git - Ignore node_modules folder everywhere

you can do it with SVN/Tortoise git as well.

just right click on node_modules -> Tortoise git -> add to ignore list.

This will generate .gitIgnore for you and you won't find node_modules folder in staging again.

MD5 is 128 bits but why is it 32 characters?

A hex "character" (nibble) is different from a "character"

To be clear on the bits vs byte, vs characters.

  • 1 byte is 8 bits (for our purposes)
  • 8 bits provides 2**8 possible combinations: 256 combinations

When you look at a hex character,

  • 16 combinations of [0-9] + [a-f]: the full range of 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
  • 16 is less than 256, so one one hex character does not store a byte.
  • 16 is 2**4: that means one hex character can store 4 bits in a byte (half a byte).
  • Therefore, two hex characters, can store 8 bits, 2**8 combinations.
  • A byte represented as a hex character is [0-9a-f][0-9a-f] and that represents both halfs of a byte (we call a half-byte a nibble).

When you look at a regular single-byte character, (we're totally going to skip multi-byte and wide-characters here)

  • It can store far more than 16 combinations.
  • The capabilities of the character are determined by the encoding. For instance, the ISO 8859-1 that stores an entire byte, stores all this stuff
  • All that stuff takes the entire 2**8 range.
  • If a hex-character in an md5() could store all that, you'd see all the lowercase letters, all the uppercase letters, all the punctuation and things like ¡°ÀÐàð, whitespace like (newlines, and tabs), and control characters (which you can't even see and many of which aren't in use).

So they're clearly different and I hope that provides the best break down of the differences.

Output single character in C

char variable = 'x';  // the variable is a char whose value is lowercase x

printf("<%c>", variable); // print it with angle brackets around the character

Testing HTML email rendering

You could also use PutsMail to test your emails before sending them.

PutsMail is a tool to test HTML emails that will be sent as campaigns, newsletters and others (please, don't use it to spam, help us to make a better world).

Main features:

  • Check HTML & CSS compatibility with email clients
  • Easily send HTML emails for approval or to check how it looks like in email clients

Proper way to empty a C-String

It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.

This will also work:

buffer[0] = '\0';

If you want to zero the entire contents of the string, you can do it this way:

memset(buffer,0,strlen(buffer));

but this will only work for zeroing up to the first NULL character.

If the string is a static array, you can use:

memset(buffer,0,sizeof(buffer));

Tomcat 7 "SEVERE: A child container failed during start"

I recently moved to a new PC all my eclipse projects. I experienced this issue. What i did was:

  1. removed the project from tomcat
  2. clean tomcat
  3. run project in tomcat

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector".

See Java GC FAQ, question 22 for more information.

Note that there are some known bugs with UseParNewGC

How to use HTML to print header and footer on every printed page of a document?

Based on some post, i think position: fixed works for me.

_x000D_
_x000D_
body {_x000D_
  background: #eaeaed;_x000D_
  -webkit-print-color-adjust: exact;_x000D_
}_x000D_
_x000D_
.my-footer {_x000D_
  background: #2db34a;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}_x000D_
_x000D_
.my-header {_x000D_
  background: red;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset=utf-8 />_x000D_
  <title>Header & Footer</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div>_x000D_
    <div class="my-header">Fixed Header</div>_x000D_
    <div class="my-footer">Fixed Footer</div>_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr>_x000D_
          <th>TH 1</th>_x000D_
          <th>TH 2</th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Press Ctrl+P in chrome see the header & footer text on each page. Hope it helps

Figuring out whether a number is a Double in Java

Try this:

if (items.elementAt(1) instanceof Double) {
   sum.add( i, items.elementAt(1));
}

How to get image size (height & width) using JavaScript?

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';

Eclipse : Failed to connect to remote VM. Connection refused.

As suat said, most of the time the connection refused is due to the fact that the port you set up is in use or there is a difference between the port number in your remote application debugging configuration in Eclipse and the port number used in the address attribute in

-Xrunjdwp:transport=dt_socket,address=1044,server=y,suspend=n.

Check those things. Thanks!

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

In my case, I left out wrapper sub folder while copying gradle folder and got the same error.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

make sure you have the correct folder structure if you copy wrapper from other location.

+-- build.gradle
+-- gradle
¦   +-- wrapper
¦       +-- gradle-wrapper.jar
¦       +-- gradle-wrapper.properties
+-- gradlew
+-- gradlew.bat
+-- settings.gradle

How do I get the Date & Time (VBS)

This is an old question but alot of the answers in here use VB or VBA. The tag says vbscript (which is how I got here).

The answers here got kind of muddled since VB is super broad where you can have so many applications of it. My answer is solely on vbscript and accomplishes my case of formatting in YYYYMMDD in vbscript

Sharing what I've learned:

  1. There are all the DateTime functions in vbscript defined here so you can mix-n-match to get the result that you want
  2. What I needed was to get the current date and format it in YYYYMMDD to do that I just needed to concat DatePart like so for the current Date: date = DatePart("yyyy",Date) & DatePart("m",Date) & DatePart("d",Date)

That's all, I hope this helps someone.

Equivalent to 'app.config' for a library (DLL)

public class ConfigMan
{
    #region Members

    string _assemblyLocation;
    Configuration _configuration;

    #endregion Members

    #region Constructors

    /// <summary>
    /// Loads config file settings for libraries that use assembly.dll.config files
    /// </summary>
    /// <param name="assemblyLocation">The full path or UNC location of the loaded file that contains the manifest.</param>
    public ConfigMan(string assemblyLocation)
    {
        _assemblyLocation = assemblyLocation;
    }

    #endregion Constructors

    #region Properties

    Configuration Configuration
    {
        get
        {
            if (_configuration == null)
            {
                try
                {
                    _configuration = ConfigurationManager.OpenExeConfiguration(_assemblyLocation);
                }
                catch (Exception exception)
                {
                }
            }
            return _configuration;
        }
    }

    #endregion Properties

    #region Methods

    public string GetAppSetting(string key)
    {
        string result = string.Empty;
        if (Configuration != null)
        {
            KeyValueConfigurationElement keyValueConfigurationElement = Configuration.AppSettings.Settings[key];
            if (keyValueConfigurationElement != null)
            {
                string value = keyValueConfigurationElement.Value;
                if (!string.IsNullOrEmpty(value)) result = value;
            }
        }
        return result;
    }

    #endregion Methods
}

Just for something to do, I refactored the top answer into a class. The usage is something like:

ConfigMan configMan = new ConfigMan(this.GetType().Assembly.Location);
var setting = configMan.GetAppSetting("AppSettingsKey");

How do I select which GPU to run a job on?

You can also set the GPU in the command line so that you don't need to hard-code the device into your script (which may fail on systems without multiple GPUs). Say you want to run your script on GPU number 5, you can type the following on the command line and it will run your script just this once on GPU#5:

CUDA_VISIBLE_DEVICES=5, python test_script.py

SQL Add foreign key to existing column

Maybe you got your columns backwards??

ALTER TABLE Employees
ADD FOREIGN KEY (UserID)           <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id)   <-- this needs to be a column of the ActiveDirectories table

Could it be that the column is called ID in the Employees table, and UserID in the ActiveDirectories table?

Then your command should be:

ALTER TABLE Employees
ADD FOREIGN KEY (ID)                   <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID)   <-- column in table "ActiveDirectories" 

Sorting list based on values from another list

list1 = ['a','b','c','d','e','f','g','h','i']
list2 = [0,1,1,0,1,2,2,0,1]

output=[]
cur_loclist = []

To get unique values present in list2

list_set = set(list2)

To find the loc of the index in list2

list_str = ''.join(str(s) for s in list2)

Location of index in list2 is tracked using cur_loclist

[0, 3, 7, 1, 2, 4, 8, 5, 6]

for i in list_set:
cur_loc = list_str.find(str(i))

while cur_loc >= 0:
    cur_loclist.append(cur_loc)
    cur_loc = list_str.find(str(i),cur_loc+1)

print(cur_loclist)

for i in range(0,len(cur_loclist)):
output.append(list1[cur_loclist[i]])
print(output)

What's the difference between isset() and array_key_exists()?

Complementing (as an algebraic curiosity) the @deceze answer with the @ operator, and indicating cases where is "better" to use @ ... Not really better if you need (no log and) micro-performance optimization:

  • array_key_exists: is true if a key exists in an array;
  • isset: is true if the key/variable exists and is not null [faster than array_key_exists];
  • @$array['key']: is true if the key/variable exists and is not (null or '' or 0); [so much slower?]
$a = array('k1' => 'HELLO', 'k2' => null, 'k3' => '', 'k4' => 0);

print isset($a['k1'])? "OK $a[k1].": 'NO VALUE.';            // OK
print array_key_exists('k1', $a)? "OK $a[k1].": 'NO VALUE.'; // OK
print @$a['k1']? "OK $a[k1].": 'NO VALUE.';                  // OK
// outputs OK HELLO.  OK HELLO. OK HELLO.

print isset($a['k2'])? "OK $a[k2].": 'NO VALUE.';            // NO
print array_key_exists('k2', $a)? "OK $a[k2].": 'NO VALUE.'; // OK
print @$a['k2']? "OK $a[k2].": 'NO VALUE.';                  // NO
// outputs NO VALUE.  OK .  NO VALUE.

print isset($a['k3'])? "OK $a[k3].": 'NO VALUE.';            // OK
print array_key_exists('k3', $a)? "OK $a[k3].": 'NO VALUE.'; // OK
print @$a['k3']? "OK $a[k3].": 'NO VALUE.';                  // NO
// outputs OK . OK . NO VALUE.

print isset($a['k4'])? "OK $a[k4].": 'NO VALUE.';            // OK
print array_key_exists('k4', $a)? "OK $a[k4].": 'NO VALUE.'; // OK
print @$a['k4']? "OK $a[k4].": 'NO VALUE.';                  // NO
// outputs OK 0. OK 0. NO VALUE

PS: you can change/correct/complement this text, it is a Wiki.

Converting String to Double in Android

I would do it this way:

try {
  txtProt = (EditText) findViewById(R.id.Protein); // Same
  p = txtProt.getText().toString(); // Same
  protein = Double.parseDouble(p); // Make use of autoboxing.  It's also easier to read.
} catch (NumberFormatException e) {
  // p did not contain a valid double
}

EDIT: "the program force closes immediately without leaving any info in the logcat"

I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

Can't choose class as main class in IntelliJ

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

Change limit for "Mysql Row size too large"

After spending hours I have found the solution: just run the following SQL in your MySQL admin to convert the table to MyISAM:

USE db_name;
ALTER TABLE table_name ENGINE=MYISAM;

Cancel a vanilla ECMAScript 6 Promise chain

Promise can be cancelled with the help of AbortController.

Is there a method for clearing then: yes you can reject the promise with AbortController object and then the promise will bypass all then blocks and go directly to the catch block.

Example:

import "abortcontroller-polyfill";

let controller = new window.AbortController();
let signal = controller.signal;
let elem = document.querySelector("#status")

let example = (signal) => {
    return new Promise((resolve, reject) => {
        let timeout = setTimeout(() => {
            elem.textContent = "Promise resolved";
            resolve("resolved")
        }, 2000);

        signal.addEventListener('abort', () => {
            elem.textContent = "Promise rejected";
            clearInterval(timeout);
            reject("Promise aborted")
        });
    });
}

function cancelPromise() {
    controller.abort()
    console.log(controller);
}

example(signal)
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log("Catch: ", error)
    });

document.getElementById('abort-btn').addEventListener('click', cancelPromise);

Html


    <button type="button" id="abort-btn" onclick="abort()">Abort</button>
    <div id="status"> </div>

Note: need to add polyfill, not supported in all browser.

Live Example

Edit elegant-lake-5jnh3

gpg: no valid OpenPGP data found

I had a similar issue.

The command I used was as follows:

wget -qO https://download.jitsi.org/jitsi-key.gpg.key |  apt-key add -

I forgot a hyphen between the flags and the URL, which is why wget threw an error.

This is the command that finally worked for me:

wget -qO - https://download.jitsi.org/jitsi-key.gpg.key |  apt-key add -

How can I read the client's machine/computer name from the browser?

Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.

EDIT: Not possible across all browser at least.

Auto-indent spaces with C in vim?

and always remember this venerable explanation of Spaces + Tabs:

http://www.jwz.org/doc/tabs-vs-spaces.html

Extracting time from POSIXct

The data.table package has a function 'as.ITime', which can do this efficiently use below:

library(data.table)
x <- "2012-03-07 03:06:49 CET"
as.IDate(x) # Output is "2012-03-07"
as.ITime(x) # Output is "03:06:49"

how to display full stored procedure code?

You can also get by phpPgAdmin if you are configured it in your system,

Step 1: Select your database

Step 2: Click on find button

Step 3: Change search option to functions then click on Find.

You will get the list of defined functions.You can search functions by name also, hope this answer will help others.

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

c++ custom compare function for std::sort()

std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

std::vector<pair<K,V>> items; 
std::sort(items.begin(), items.end()); 

If you really need to provide your own comparison function, then you need something along the lines of

template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
  return lhs.first < rhs.first;
}

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

Android Drawing Separator/Divider Line in Layout?

This would help you to resolve this problem. Here a small view is created to make a black line as a separator between two views.

 <View
        android:layout_width="3dp"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
         />

Creating default object from empty value in PHP?

This message has been E_STRICT for PHP <= 5.3. Since PHP 5.4, it was unluckilly changed to E_WARNING. Since E_WARNING messages are useful, you don't want to disable them completely.

To get rid of this warning, you must use this code:

if (!isset($res)) 
    $res = new stdClass();

$res->success = false;

This is fully equivalent replacement. It assures exactly the same thing which PHP is silently doing - unfortunatelly with warning now - implicit object creation. You should always check if the object already exists, unless you are absolutely sure that it doesn't. The code provided by Michael is no good in general, because in some contexts the object might sometimes be already defined at the same place in code, depending on circumstances.

What LaTeX Editor do you suggest for Linux?

There is a pretty good list at linuxappfinder.com.

My personal preference for LaTeX on Linux has been the KDE-based editor Kile.

Sorting an array in C?

In your particular case the fastest sort is probably the one described in this answer. It is exactly optimized for an array of 6 ints and uses sorting networks. It is 20 times (measured on x86) faster than library qsort. Sorting networks are optimal for sort of fixed length arrays. As they are a fixed sequence of instructions they can even be implemented easily by hardware.

Generally speaking there is many sorting algorithms optimized for some specialized case. The general purpose algorithms like heap sort or quick sort are optimized for in place sorting of an array of items. They yield a complexity of O(n.log(n)), n being the number of items to sort.

The library function qsort() is very well coded and efficient in terms of complexity, but uses a call to some comparizon function provided by user, and this call has a quite high cost.

For sorting very large amount of datas algorithms have also to take care of swapping of data to and from disk, this is the kind of sorts implemented in databases and your best bet if you have such needs is to put datas in some database and use the built in sort.

Eclipse reports rendering library more recent than ADT plug-in

  1. Click Help > Install New Software.
  2. In the Work with field, enter: https://dl-ssl.google.com/android/eclipse/
  3. Select Developer Tools / Android Development Tools.
  4. Click Next and complete the wizard.

JavaFX "Location is required." even though it is in the same package

This problem can be caused by incorrect path to the FXML file.

If you're using absolute paths (my/package/views/view.fxml), you have to precede then with a slash:

getClass().getResource("/my/package/views/view.fxml")

You can use relative paths as well:

getClass().getResource("views/view.fxml")

Creating a UICollectionView programmatically

colection view exam

    #import "CollectionViewController.h"
#import "BuyViewController.h"
#import "CollectionViewCell.h"

@interface CollectionViewController ()
{
    NSArray *mobiles;
    NSArray  *costumes;
    NSArray *shoes;
    NSInteger selectpath;
    NSArray *mobilerate;
    NSArray *costumerate;
    NSArray *shoerate;
}
@end

@implementation CollectionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = self.receivename;
    mobiles = [[NSArray alloc]initWithObjects:@"7.jpg",@"6.jpg",@"5.jpg", nil];
    costumes = [[NSArray alloc]initWithObjects:@"shirt.jpg",@"costume2.jpg",@"costume1.jpg", nil];
    shoes = [[NSArray alloc]initWithObjects:@"shoe.jpg",@"shoe1.jpg",@"shoe2.jpg", nil];
    mobilerate = [[NSArray alloc]initWithObjects:@"10000",@"11000",@"13000",nil];
    costumerate = [[NSArray alloc]initWithObjects:@"699",@"999",@"899", nil];
    shoerate = [[NSArray alloc]initWithObjects:@"599",@"499",@"300", nil];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];

    UIImageView *collectionImg = (UIImageView *)[cell viewWithTag:100];

    if ([self.receivename isEqualToString:@"Mobiles"])
    {
        collectionImg.image = [UIImage imageNamed:[mobiles objectAtIndex:indexPath.row]];
    }
    else if ([self.receivename isEqualToString:@"Costumes"])
    {
        collectionImg.image = [UIImage imageNamed:[costumes objectAtIndex:indexPath.row]];
    }
    else
    {
        collectionImg.image = [UIImage imageNamed:[shoes objectAtIndex:indexPath.row]];
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{
    selectpath = indexPath.row;
    [self performSegueWithIdentifier:@"buynow" sender:self];
}

    // In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"buynow"])
    {
        BuyViewController *obj = segue.destinationViewController;
        if ([self.receivename isEqualToString:@"Mobiles"])
        {
            obj.reciveimg = [mobiles objectAtIndex:selectpath];
            obj.labelrecive = [mobilerate objectAtIndex:selectpath];

        }
        else if ([self.receivename isEqualToString:@"Costumes"])
        {
            obj.reciveimg = [costumes objectAtIndex:selectpath];
            obj.labelrecive = [costumerate objectAtIndex:selectpath];
        }
        else
        {
            obj.reciveimg = [shoes objectAtIndex:selectpath];
            obj.labelrecive = [shoerate objectAtIndex:selectpath];
        }
        //     Get the new view controller using [segue destinationViewController].
        //     Pass the selected object to the new view controller.
    }
}

@end

.h file

@interface CollectionViewController :
UIViewController<UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) NSString *receiveimg;
@property (strong,nonatomic) NSString *receivecostume;
@property (strong,nonatomic)NSString *receivename;

@end

Counting null and non-null values in a single query

I created the table in postgres 10 and both of the following worked:

select count(*) from us

and

select count(a is null) from us

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

Array functions in jQuery

An easy way to get the max and min value in an array is as follows. This has been explained at get max & min values in array

var myarray = [5,8,2,4,11,7,3];
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};

// Function to get the Min value in Array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
// Usage 
alert(Array.max(myarray));
alert(Array.min(myarray));

Is Constructor Overriding Possible?

Constructor overriding is not possible because of following reason.

Constructor name must be the same name of class name. In Inheritance practice you need to create two classes with different names hence two constructors must have different names. So constructor overriding is not possible and that thought not even make sense.

Selecting only numeric columns from a data frame

Filter() from the base package is the perfect function for that use-case: You simply have to code:

Filter(is.numeric, x)

It is also much faster than select_if():

library(microbenchmark)
microbenchmark(
    dplyr::select_if(mtcars, is.numeric),
    Filter(is.numeric, mtcars)
)

returns (on my computer) a median of 60 microseconds for Filter, and 21 000 microseconds for select_if (350x faster).

Bootstrap 3 Multi-column within a single ul not floating properly

You should try using the Grid Template.

Here's what I've used for a two Column Layout of a <ul>

<ul class="list-group row">
     <li class="list-group-item col-xs-6">Row1</li>
     <li class="list-group-item col-xs-6">Row2</li>
     <li class="list-group-item col-xs-6">Row3</li>
     <li class="list-group-item col-xs-6">Row4</li>
     <li class="list-group-item col-xs-6">Row5</li>
</ul>

This worked for me.

AngularJs event to call after content is loaded

var myTestApp = angular.module("myTestApp", []); 
myTestApp.controller("myTestController", function($scope, $window) {
$window.onload = function() {
 alert("is called on page load.");
};
});

Unable to read repository at http://download.eclipse.org/releases/indigo

Had this problem in Linux, and I found that the user doesn't have permission to update the eclipse directory

change the owner of eclipse folder recursively, or run eclipse with user who has write permission to the folder

How to get the list of files in a directory in a shell script?

for entry in "$search_dir"/* "$work_dir"/*
do
  if [ -f "$entry" ];then
    echo "$entry"
  fi
done

How to flip background image using CSS?

You can flip both vertical and horizontal at the same time

    -moz-transform: scaleX(-1) scaleY(-1);
    -o-transform: scaleX(-1) scaleY(-1);
    -webkit-transform: scaleX(-1) scaleY(-1);
    transform: scaleX(-1) scaleY(-1);

And with the transition property you can get a cool flip

    -webkit-transition: transform .4s ease-out 0ms;
    -moz-transition: transform .4s ease-out 0ms;
    -o-transition: transform .4s ease-out 0ms;
    transition: transform .4s ease-out 0ms;
    transition-property: transform;
    transition-duration: .4s;
    transition-timing-function: ease-out;
    transition-delay: 0ms;

Actually it flips the whole element, not just the background-image

SNIPPET

_x000D_
_x000D_
function flip(){_x000D_
 var myDiv = document.getElementById('myDiv');_x000D_
 if (myDiv.className == 'myFlipedDiv'){_x000D_
  myDiv.className = '';_x000D_
 }else{_x000D_
  myDiv.className = 'myFlipedDiv';_x000D_
 }_x000D_
}
_x000D_
#myDiv{_x000D_
  display:inline-block;_x000D_
  width:200px;_x000D_
  height:20px;_x000D_
  padding:90px;_x000D_
  background-color:red;_x000D_
  text-align:center;_x000D_
  -webkit-transition:transform .4s ease-out 0ms;_x000D_
  -moz-transition:transform .4s ease-out 0ms;_x000D_
  -o-transition:transform .4s ease-out 0ms;_x000D_
  transition:transform .4s ease-out 0ms;_x000D_
  transition-property:transform;_x000D_
  transition-duration:.4s;_x000D_
  transition-timing-function:ease-out;_x000D_
  transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
  -moz-transform:scaleX(-1) scaleY(-1);_x000D_
  -o-transform:scaleX(-1) scaleY(-1);_x000D_
  -webkit-transform:scaleX(-1) scaleY(-1);_x000D_
  transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
_x000D_
_x000D_

ReactJS: Warning: setState(...): Cannot update during an existing state transition

I am giving a generic example for better understanding, In the following code

render(){
    return(
      <div>

        <h3>Simple Counter</h3>
        <Counter
          value={this.props.counter}
          onIncrement={this.props.increment()} <------ calling the function
          onDecrement={this.props.decrement()} <-----------
          onIncrementAsync={this.props.incrementAsync()} />
      </div>
    )
  }

When supplying props I am calling the function directly, this wold have a infinite loop execution and would give you that error, Remove the function call everything works normally.

render(){
    return(
      <div>

        <h3>Simple Counter</h3>
        <Counter
          value={this.props.counter}
          onIncrement={this.props.increment} <------ function call removed
          onDecrement={this.props.decrement} <-----------
          onIncrementAsync={this.props.incrementAsync} />
      </div>
    )
  }

How to remove all white space from the beginning or end of a string?

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

Download a file with Android, and showing the progress in a ProgressDialog

While I was starting to learn android development, I had learnt that ProgressDialog is the way to go. There is the setProgress method of ProgressDialog which can be invoked to update the progress level as the file gets downloaded.

The best I have seen in many apps is that they customize this progress dialog's attributes to give a better look and feel to the progress dialog than the stock version. Good to keeping the user engaged with some animation of like frog, elephant or cute cats/puppies. Any animation with in the progress dialog attracts users and they don't feel like being kept waiting for long.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

I hope this helps .. I got this same error message (Server not found in Kerberos database (7)) but this occurs after the successful use of the keytab to login.

The error message occurs when we attempt to use the credentials to do LDAP searches against AD.

This has only started happening since java 1.6.0_34 - it worked with 1.6.0_31 which I think was previous release. The error occurs because the java doesn't trust that the KDC it is communicating with for LDAP is actually part of the Kerberos realm. In our case, I think it is because the LDAP connection is made with the server name found via the round-robin'd resolved query. That is, java resolves realm.example.com, but gets any one of kdc1.example.com or kdc2.example .com ..etc). They must have tightened the checking betweeen these releases.

In our case the problem was worked around by setting the ldap server name directly rather than relying on DNS.

But investigations continue.

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.

Detect merged cells in VBA Excel with MergeArea

While working with selected cells as shown by @tbur can be useful, it's also not the only option available.

You can use Range() like so:

If Worksheets("Sheet1").Range("A1").MergeCells Then
  Do something
Else
  Do something else
End If

Or:

If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
  Do something
Else
  Do something else
End If

Alternately, you can use Cells():

If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
  Do something
Else
  Do something else
End If

How to edit Docker container files from the host?

The following worked for me

docker run -it IMAGE_NAME /bin/bash

eg. my image was called ipython/notebook

docker run -it ipython/notebook /bin/bash

Creating a UIImage from a UIColor to use as a background image for UIButton

I created a category around UIButton to be able to set the background color of the button and set the state. You might find this useful.

@implementation  UIButton (ButtonMagic)

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state];
}

+ (UIImage *)imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

This will be part of a set of helper categories I'm open sourcing this month.

Swift 2.2

extension UIImage {
static func fromColor(color: UIColor) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    CGContextSetFillColorWithColor(context, color.CGColor)
    CGContextFillRect(context, rect)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return img
  }
}

Swift 3.0

extension UIImage {
    static func from(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
}

Use as

let img = UIImage.from(color: .black)

Running Python from Atom

To run the python file on mac.

  1. Open the preferences in atom ide. To open the preferences press 'command + . ' ( ? + , )
  2. Click on the install in the preferences to install packages.

  3. Search for package "script" and click on install

  4. Now open the python file(with .py extension ) you want to run and press 'control + r ' (^ + r)

PHP - Notice: Undefined index:

Before you extract values from $_POST, you should check if they exist. You could use the isset function for this (http://php.net/manual/en/function.isset.php)

a href link for entire div in HTML/CSS

Why don't you strip out the <div> element and replace it with an <a> instead? Just because the anchor tag isn't a div doesn't mean you can't style it with display:block, a height, width, background, border, etc. You can make it look like a div but still act like a link. Then you're not relying on invalid code or JavaScript that may not be enabled for some users.