Programs & Examples On #Browser security

Android: How to bind spinner to custom object list?

Works fine for me, the code needed around the getResource() thing is as follows:

spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> spinner, View v,
                int arg2, long arg3) {
            String selectedVal = getResources().getStringArray(R.array.compass_rate_values)[spinner.getSelectedItemPosition()];
            //Do something with the value
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    });

Just need to make sure (by yourself) the values in the two arrays are aligned properly!

How to change the window title of a MATLAB plotting figure?

If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:

  1. Go to "Edit" in the figure window

  2. Go to "Figure Properties"

  3. At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".

That's all.

Good luck.

How to search for file names in Visual Studio?

Just for anyone else landing on this page from Google or elsewhere, this answer is probably the best answer out of all of them.

To summarize, simply hit:

CTRL + ,

And then start typing the file name.

Python Pandas: Get index of rows which column matches certain value

Can be done using numpy where() function:

import pandas as pd
import numpy as np

In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
       index=list("abcde"))

In [717]: df
Out[717]: 
  BoolCol gene_name
a   False   SLC45A1
b    True    NECAP2
c   False     CLIC4
d    True       ADC
e    True     AGBL4

In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)

In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])

In [720]: df.iloc[select_indices]
Out[720]: 
  BoolCol gene_name
b    True    NECAP2
d    True       ADC
e    True     AGBL4

Though you don't always need index for a match, but incase if you need:

In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')

In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']

Chrome Extension - Get DOM content

You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScriptinstead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.

part of manifest.json

"browser_action": {
    "default_title": "Test",
    "default_popup": "index.html"
},
"permissions": [
    "activeTab",
    "<all_urls>"
]

index.html

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button id="test">TEST!</button>
    <script src="test.js"></script>
  </body>
</html>

test.js

document.getElementById("test").addEventListener('click', () => {
    console.log("Popup DOM fully loaded and parsed");

    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        console.log('Tab script:');
        console.log(document.body);
        return document.body.innerHTML;
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure
        console.log('Popup script:')
        console.log(results[0]);
    });
});

Define static method in source-file with declaration in header-file in C++

You don't need to have static in function definition

What does "zend_mm_heap corrupted" mean

Look for any module that uses buffering, and selectively disable it.

I'm running PHP 5.3.5 on CentOS 4.8, and after doing this I found eaccelerator needed an upgrade.

Populating VBA dynamic arrays

As Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve. Brett suggested Mod to do this.

You can also use a user defined Type and Sub to do this. Consider my code below:

Public Type dsIntArrayType
   eElems() As Integer
   eSize As Integer
End Type

Public Sub PushBackIntArray( _
    ByRef dsIntArray As dsIntArrayType, _
    ByVal intValue As Integer)

    With dsIntArray
    If UBound(.eElems) < (.eSize + 1) Then
        ReDim Preserve .eElems(.eSize * 2 + 1)
    End If
    .eSize = .eSize + 1
    .eElems(.eSize) = intValue
    End With

End Sub

This calls ReDim Preserve only when the size has doubled. The member variable eSize keeps track of the actual data size of eElems. This approach has helped me improve performance when final array length is not known until run time.

Hope this helps others too.

Using multiple IF statements in a batch file

Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.

For the OP's question it sounds like you require two specific files to exist. Just use a tally:

IF EXIST somefile.txt (
    set /a file1_status=1
)

IF EXIST someotehrfile.txt (
    set /a file2_status=1
)

set /a file_status_result=file1_status + file2_status

if %file_status_result% equ 2 (
    goto somefileexists
)

goto exit

:somefileexists
IF EXIST someotherfile.txt SET var=...

:exit

My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.

jQuery vs. javascript?

Jquery like any other good JavaScript frameworks supplies you with functionality independent of browser platform wrapping all the intricacies, which you may not care about or don't want to care about.

I think using a framework is better instead of using pure JavaScript and doing all the stuff from scratch, unless you usage is very limited.

I definitely recommend JQuery!

Thanks

Is there a way to pass optional parameters to a function?

You can specify a default value for the optional argument with something that would never passed to the function and check it with the is operator:

class _NO_DEFAULT:
    def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()

def func(optional= _NO_DEFAULT):
    if optional is _NO_DEFAULT:
        print("the optional argument was not passed")
    else:
        print("the optional argument was:",optional)

then as long as you do not do func(_NO_DEFAULT) you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:

# these two work the same as using **
func()
func(optional=1)

# the optional argument can be positional or keyword unlike using **
func(1) 

#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)

Show spinner GIF during an $http request in AngularJS?

create directive with this code:

$scope.$watch($http.pendingRequests, toggleLoader);

function toggleLoader(status){
  if(status.length){
    element.addClass('active');
  } else {
    element.removeClass('active');
  }
}

How to get the last character of a string in a shell?

Try:

"${str:$((${#str}-1)):1}"

For e.g.:

someone@mypc:~$ str="A random string*"; echo "$str"
A random string*
someone@mypc:~$ echo "${str:$((${#str}-1)):1}"
*
someone@mypc:~$ echo "${str:$((${#str}-2)):1}"
g

jQuery table sort

By far, the easiest one I've used is: http://datatables.net/

Amazingly simple...just make sure if you go the DOM replacement route (IE, building a table and letting DataTables reformat it) then make sure to format your table with <thead> and <tbody> or it won't work. That's about the only gotcha.

There's also support for AJAX, etc. As with all really good pieces of code, it's also VERY easy to turn it all off. You'd be suprised what you might use, though. I started with a "bare" DataTable that only sorted one field and then realized that some of the features were really relevant to what I'm doing. Clients LOVE the new features.

Bonus points to DataTables for full ThemeRoller support....

I've also had ok luck with tablesorter, but it's not nearly as easy, not quite as well documented, and has only ok features.

show icon in actionbar/toolbar with AppCompat-v7 21

if you want to set the home or back icon (not logo or static icon) so you can use

 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
 getSupportActionBar().setHomeAsUpIndicator( getResources().getDrawable(R.drawable.home) );

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

If you're recompiling a disassembled APK with APK tool:

Just Set Memory Allocation a little bigger

set switch -Xmx1024mto -Xmx2048m

java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"

you're good to go.. :)

Clear back stack using fragments

I just wanted to add :--

Popping out from backstack using following

fragmentManager.popBackStack()

is just about removing the fragments from the transaction, no way it is going to remove the fragment from the screen. So ideally, it may not be visible to you but there may be two or three fragments stacked over each other, and on back key press the UI may look cluttered,stacked.

Just taking a simple example:-

Suppose you have a fragmentA which loads Fragmnet B using fragmentmanager.replace() and then we do addToBackStack, to save this transaction. So the flow is :--

STEP 1 -> FragmentA->FragmentB (we moved to FragmentB, but Fragment A is in background, not visible).

Now You do some work in fragmentB and press the Save button—which after saving should go back to fragmentA.

STEP 2-> On save of FragmentB, we go back to FragmentA.

STEP 3 ->So common mistake would be... in Fragment B,we will do fragment Manager.replace() fragmentB with fragmentA.

But what actually is happenening, we are loading Fragment A again, replacing FragmentB . So now there are two FragmentA (one from STEP-1, and one from this STEP-3).

Two instances of FragmentsA are stacked over each other, which may not be visible , but it is there.

So even if we do clear the backstack by above methods, the transaction is cleared but not the actual fragments. So ideally in such a particular case, on press of save button you simply need to go back to fragmentA by simply doing fm.popBackStack() or fm.popBackImmediate().

So correct Step3-> fm.popBackStack() go back to fragmentA, which is already in memory.

How to change the Content of a <textarea> with JavaScript

Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:

document.forms['yourform']['yourtextarea'].value = 'yourvalue';

where in the HTML your textarea is nested somewhere in a form like this:

<form name="yourform">
    <textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>

And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.

What is the difference between linear regression and logistic regression?

The basic difference between Linear Regression and Logistic Regression is : Linear Regression is used to predict a continuous or numerical value but when we are looking for predicting a value that is categorical Logistic Regression come into picture.

Logistic Regression is used for binary classification.

Java List.add() UnsupportedOperationException

You must initialize your List seeAlso :

List<String> seeAlso = new Vector<String>();

or

List<String> seeAlso = new ArrayList<String>();

Find index of last occurrence of a substring in a string

you can use rindex() function to get the last occurrence of a character in string

s="hellloooloo"
b='l'
print(s.rindex(b))

Fastest Way to Find Distance Between Two Lat/Long Points

if you are using MySQL 5.7.*, then you can use st_distance_sphere(POINT, POINT).

Select st_distance_sphere(POINT(-2.997065, 53.404146 ), POINT(58.615349, 23.56676 ))/1000  as distcance

How to check if a file is empty in Bash?

I came here looking for how to delete empty __init__.py files as they are implicit in Python 3.3+ and ended up using:

find -depth '(' -type f  -name __init__.py ')' -print0 |
  while IFS= read -d '' -r file; do if [[ ! -s $file ]]; then rm $file; fi; done

Also (at least in zsh) using $path as the variable also breaks your $PATH env and so it'll break your open shell. Anyway, thought I'd share!

How to round a number to n decimal places in Java

double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;

How can I disable the bootstrap hover color for links?

Mark color: #005580; as color: #005580 !important;.

It will override default bootstrap hover.

Tab separated values in awk

Use:

awk -v FS='\t' -v OFS='\t' ...

Example from one of my scripts.

I use the FS and OFS variables to manipulate BIND zone files, which are tab delimited:

awk -v FS='\t' -v OFS='\t' \
    -v record_type=$record_type \
    -v hostname=$hostname \
    -v ip_address=$ip_address '
$1==hostname && $3==record_type {$4=ip_address}
{print}
' $zone_file > $temp

This is a clean and easy to read way to do this.

Are there any standard exit status codes in Linux?

To a first approximation, 0 is success, non-zero is failure, with 1 being general failure, and anything larger than one being a specific failure. Aside from the trivial exceptions of false and test, which are both designed to give 1 for success, there's a few other exceptions I found.

More realistically, 0 means success or maybe failure, 1 means general failure or maybe success, 2 means general failure if 1 and 0 are both used for success, but maybe sucess as well.

The diff command gives 0 if files compared are identical, 1 if they differ, and 2 if binaries are different. 2 also means failure. The less command gives 1 for failure unless you fail to supply an argument, in which case, it exits 0 despite failing.

The more command and the spell command give 1 for failure, unless the failure is a result of permission denied, nonexistent file, or attempt to read a directory. In any of these cases, they exit 0 despite failing.

Then the expr command gives 1 for success unless the output is the empty string or zero, in which case, 0 is success. 2 and 3 are failure.

Then there's cases where success or failure is ambiguous. When grep fails to find a pattern, it exits 1, but it exits 2 for a genuine failure (like permission denied). Klist also exits 1 when it fails to find a ticket, although this isn't really any more of a failure than when grep doesn't find a pattern, or when you ls an empty directory.

So, unfortunately, the unix powers that be don't seem to enforce any logical set of rules, even on very commonly used executables.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How to echo out table rows from the db (php)

 $result= mysql_query("SELECT * FROM MY_TABLE");
 while($row = mysql_fetch_array($result)){
      echo $row['whatEverColumnName'];
 }

How to write header row with csv.DictWriter?

Another way to do this would be to add before adding lines in your output, the following line :

output.writerow(dict(zip(dr.fieldnames, dr.fieldnames)))

The zip would return a list of doublet containing the same value. This list could be used to initiate a dictionary.

Write Array to Excel Range

add ExcelUtility class to your project and enjoy it.

ExcelUtility.cs File content:

using System;
using Microsoft.Office.Interop.Excel;

static class ExcelUtility
{
    public static void WriteArray<T>(this _Worksheet sheet, int startRow, int startColumn, T[,] array)
    {
        var row = array.GetLength(0);
        var col = array.GetLength(1);
        Range c1 = (Range) sheet.Cells[startRow, startColumn];
        Range c2 = (Range) sheet.Cells[startRow + row - 1, startColumn + col - 1];
        Range range = sheet.Range[c1, c2];
        range.Value = array;
    }

    public static bool SaveToExcel<T>(T[,] data, string path)
    {
        try
        {
            //Start Excel and get Application object.
            var oXl = new Application {Visible = false};

            //Get a new workbook.
            var oWb = (_Workbook) (oXl.Workbooks.Add(""));
            var oSheet = (_Worksheet) oWb.ActiveSheet;
            //oSheet.WriteArray(1, 1, bufferData1);

            oSheet.WriteArray(1, 1, data);

            oXl.Visible = false;
            oXl.UserControl = false;
            oWb.SaveAs(path, XlFileFormat.xlWorkbookDefault, Type.Missing,
                Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            oWb.Close(false);
            oXl.Quit();
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }
}

usage :

var data = new[,]
{
    {11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
    {21, 22, 23, 24, 25, 26, 27, 28, 29, 30},
    {31, 32, 33, 34, 35, 36, 37, 38, 39, 40}
};

ExcelUtility.SaveToExcel(data, "test.xlsx");

Best Regards!

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

Set selected option of select box

// Make option have a "selected" attribute using jQuery

var yourValue = "Gateway 2";

$("#gate").find('option').each(function( i, opt ) {
    if( opt.value === yourValue ) 
        $(opt).attr('selected', 'selected');
});

How to make HTML open a hyperlink in another window or tab?

below example with target="_blank" works for Safari and Mozilla

<a href="http://www.starfall.com" `target="_blank"`>

Using target="new"worked for Chrome

<a href="http://www.starfall.com" `target="new"`>

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

TypeError: Converting circular structure to JSON in nodejs

TypeError: Converting circular structure to JSON in nodejs: This error can be seen on Arangodb when using it with Node.js, because storage is missing in your database. If the archive is created under your database, check in the Aurangobi web interface.

What methods of ‘clearfix’ can I use?

The new standard, as used by Inuit.css and Bourbon - two very widely used and well-maintained CSS/Sass frameworks:

.btcf:after {
    content:"";
    display:block;
    clear:both;
}

Notes

Keep in mind that clearfixes are essentially a hack for what flexbox layouts can now provide in a much smarter way. CSS floats were originally designed for inline content to flow around - like images in a long textual article - and not for grid layouts and the like. If your target browsers support flexbox, it's worth looking into.

This doesn't support IE7. You shouldn't be supporting IE7. Doing so continues to expose users to unfixed security exploits and makes life harder for all other web developers, as it reduces the pressure on users and organisations to switch to modern browsers.

This clearfix was announced and explained by Thierry Koblentz in July 2012. It sheds unnecessary weight from Nicolas Gallagher's 2011 micro-clearfix. In the process, it frees a pseudo-element for your own use. This has been updated to use display: block rather than display: table (again, credit to Thierry Koblentz).

How can I exclude multiple folders using Get-ChildItem -exclude?

The exclusion pattern should be case-insensitive, so you shouldn't have to specify every case for the exclusion.

That said, the -Exclude parameter accepts an array of strings, so as long as you define $archive as such, you should be set.

$archive = ("*archive*","*Archive*","*ARCHIVE*");

You also should drop the trailing asterisk from $folder - since you're specifying -recurse, you should only need to give the top-level folder.

$folder = "T:\Drawings\Design\"

Fully revised script. This also changes how you detect whether you've found a directory, and skips the Foreach-Object because you can just pull the property directly & dump it all to the file.

$folder = "T:\Drawings\Design\";
$raw_txt = "T:\Design Projects\Design_Admin\PowerShell\raw.txt";
$search_pro = "T:\Design Projects\Design_Admin\PowerShell\search.pro";
$archive = ("*archive*","*Archive*","*ARCHIVE*");

Get-ChildItem -Path $folder -Exclude $archive -Recurse  | where {$_.PSIsContainer}  | select-Object -expandproperty FullName |out-file $search_pro 

Best practice to look up Java Enum

Apache Commons Lang 3 contais the class EnumUtils. If you aren't using Apache Commons in your projects, you're doing it wrong. You are reinventing the wheel!

There's a dozen of cool methods that we could use without throws an Exception. For example:

Gets the enum for the class, returning null if not found.

This method differs from Enum.valueOf in that it does not throw an exceptionfor an invalid enum name and performs case insensitive matching of the name.

EnumUtils.getEnumIgnoreCase(SeasonEnum.class, season);

ip address validation in python using regex

Use anchors instead:

aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)

These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^ anchor because it's implicit in the .match() method).

Then, check if the regex did in fact match before trying to access its results:

if aa:
    ip = aa.group()

Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:

ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)

Here, the \b word boundary anchors make sure that the digits don't exceed 3 for each segment.

Is there a vr (vertical rule) in html?

<div style="width:1px;background-color:red;height:30px;float:right;"></div>

Easily can be done using a div like this

How to convert HTML to PDF using iTextSharp

Here's the link I used as a guide. Hope this helps!

Converting HTML to PDF using ITextSharp

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string strHtml = string.Empty;
            //HTML File path -http://aspnettutorialonline.blogspot.com/
            string htmlFileName = Server.MapPath("~") + "\\files\\" + "ConvertHTMLToPDF.htm";
            //pdf file path. -http://aspnettutorialonline.blogspot.com/
            string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "ConvertHTMLToPDF.pdf";

            //reading html code from html file
            FileStream fsHTMLDocument = new FileStream(htmlFileName, FileMode.Open, FileAccess.Read);
            StreamReader srHTMLDocument = new StreamReader(fsHTMLDocument);
            strHtml = srHTMLDocument.ReadToEnd();
            srHTMLDocument.Close();

            strHtml = strHtml.Replace("\r\n", "");
            strHtml = strHtml.Replace("\0", "");

            CreatePDFFromHTMLFile(strHtml, pdfFileName);

            Response.Write("pdf creation successfully with password -http://aspnettutorialonline.blogspot.com/");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
    public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
    {
        try
        {
            object TargetFile = FileName;
            string ModifiedFileName = string.Empty;
            string FinalFileName = string.Empty;

            /* To add a Password to PDF -http://aspnettutorialonline.blogspot.com/ */
            TestPDF.HtmlToPdfBuilder builder = new TestPDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
            TestPDF.HtmlPdfPage first = builder.AddPage();
            first.AppendHtml(HtmlStream);
            byte[] file = builder.RenderPdf();
            File.WriteAllBytes(TargetFile.ToString(), file);

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
            ModifiedFileName = TargetFile.ToString();
            ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");

            string password = "password";
            iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, password, "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
            //http://aspnettutorialonline.blogspot.com/
            reader.Close();
            if (File.Exists(TargetFile.ToString()))
                File.Delete(TargetFile.ToString());
            FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
            File.Copy(ModifiedFileName, FinalFileName);
            if (File.Exists(ModifiedFileName))
                File.Delete(ModifiedFileName);

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

You can download the sample file. Just place the html you want to convert in the files folder and run. It will automatically generate the pdf file and place it in the same folder. But in your case, you can specify your html path in the htmlFileName variable.

How unique is UUID?

Quoting from Wikipedia:

Thus, anyone can create a UUID and use it to identify something with reasonable confidence that the identifier will never be unintentionally used by anyone for anything else

It goes on to explain in pretty good detail on how safe it actually is. So to answer your question: Yes, it's safe enough.

MongoDB "root" user

The best superuser role would be the root.The Syntax is:

use admin

db.createUser(
{
    user: "root",
    pwd: "password",
    roles: [ "root" ]
})

For more details look at built-in roles.

Hope this helps !!!

window.location.href and window.open () methods in JavaScript

  • window.open will open a new browser with the specified URL.

  • window.location.href will open the URL in the window in which the code is called.

Note also that window.open() is a function on the window object itself whereas window.location is an object that exposes a variety of other methods and properties.

Error ITMS-90717: "Invalid App Store Icon"

Whatever way you try above you need to test it by upload it to app connect like me to make sure it works and save your valuable time

enter image description here

enter image description here

overlay two images in android to set an imageview

You can skip the complex Canvas manipulation and do this entirely with Drawables, using LayerDrawable. You have one of two choices: You can either define it in XML then simply set the image, or you can configure a LayerDrawable dynamically in code.

Solution #1 (via XML):

Create a new Drawable XML file, let's call it layer.xml:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/t" />
    <item android:drawable="@drawable/tt" />
</layer-list>

Now set the image using that Drawable:

testimage.setImageDrawable(getResources().getDrawable(R.layout.layer));

Solution #2 (dynamic):

Resources r = getResources();
Drawable[] layers = new Drawable[2];
layers[0] = r.getDrawable(R.drawable.t);
layers[1] = r.getDrawable(R.drawable.tt);
LayerDrawable layerDrawable = new LayerDrawable(layers);
testimage.setImageDrawable(layerDrawable);

(I haven't tested this code so there may be a mistake, but this general outline should work.)

Ruby on Rails generates model field:type - what are the options for field:type?

$ rails g model Item name:string description:text product:references

I too found the guides difficult to use. Easy to understand, but hard to find what I am looking for.

Also, I have temp projects that I run the rails generate commands on. Then once I get them working I run it on my real project.

Reference for the above code: http://guides.rubyonrails.org/getting_started.html#associating-models

How do I validate a date in this format (yyyy-mm-dd) using jquery?

You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE if everythings check out to be correct or FALSE if anything is invalid. It doesn't get easier then this!

function validateDate(date) {
    var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
    if (matches == null) return false;
    var d = matches[3];
    var m = matches[2] - 1;
    var y = matches[1] ;
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}

Be aware that months need to be subtracted like this: var m = matches[2] - 1; else the new Date() instance won't be properly made.

How to configure log4j.properties for SpringJUnit4ClassRunner?

I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.

iPad WebApp Full Screen in Safari

It only opens the first (bookmarked) page full screen. Any next page will be opened WITH the address bar visible again. Whatever meta tag you put into your page header...

Pass a variable to a PHP script running from the command line

I strongly recommend the use of getopt.

If you want help to print out for your options then take a look at GetOptionKit.

How to change the datetime format in pandas

Changing the format but not changing the type:

df['date'] = pd.to_datetime(df["date"].dt.strftime('%Y-%m'))

How can I remount my Android/system as read-write in a bash script using adb?

Probable cause that remount fails is you are not running adb as root.

Shell Script should be as follow.

# Script to mount Android Device as read/write.
# List the Devices.
adb devices;

# Run adb as root (Needs root access).
adb root;

# Since you're running as root su is not required
adb shell mount -o rw,remount /;

If this fails, you could try the below:

# List the Devices.
adb devices;

# Run adb as root
adb root;

adb remount;
adb shell su -c "mount -o rw,remount /";

To find which user you are:

$ adb shell whoami

ASP.NET Core return JSON with status code

I got this to work. My big issue was my json was a string (in my database...and not a specific/known Type).

Ok, I finally got this to work.

////[Route("api/[controller]")]
////[ApiController]
////public class MyController: Microsoft.AspNetCore.Mvc.ControllerBase
////{
                    //// public IActionResult MyMethod(string myParam) {

                    string hardCodedJson = "{}";
                    int hardCodedStatusCode = 200;

                    Newtonsoft.Json.Linq.JObject job = Newtonsoft.Json.Linq.JObject.Parse(hardCodedJson);
                    /* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
                    Microsoft.AspNetCore.Mvc.ContentResult contRes = this.Content(job.ToString());
                    contRes.StatusCode = hardCodedStatusCode;

                    return contRes;

                    //// } ////end MyMethod
              //// } ////end class

I happen to be on asp.net core 3.1

#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
//C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\3.1.0\ref\netcoreapp3.1\Microsoft.AspNetCore.Mvc.Core.dll

I got the hint from here :: https://www.jianshu.com/p/7b3e92c42b61

Change auto increment starting number?

just export the table with data .. then copy its sql like

CREATE TABLE IF NOT EXISTS `employees` (
  `emp_badgenumber` int(20) NOT NULL AUTO_INCREMENT,
  `emp_fullname` varchar(100) NOT NULL,
  `emp_father_name` varchar(30) NOT NULL,
  `emp_mobile` varchar(20) DEFAULT NULL,
  `emp_cnic` varchar(20) DEFAULT NULL,
  `emp_gender` varchar(10) NOT NULL,
  `emp_is_deleted` tinyint(4) DEFAULT '0',
  `emp_registration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `emp_overtime_allowed` tinyint(4) DEFAULT '1',
  PRIMARY KEY (`emp_badgenumber`),
  UNIQUE KEY `bagdenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber_2` (`emp_badgenumber`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=111121326 ;

now change auto increment value and execute sql.

How to run multiple sites on one apache instance

Yes with Virtual Host you can have as many parallel programs as you want:

Open

/etc/httpd/conf/httpd.conf

Listen 81
Listen 82
Listen 83

<VirtualHost *:81>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site1/html
    ServerName site1.com
    ErrorLog logs/site1-error_log
    CustomLog logs/site1-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>

<VirtualHost *:82>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site2/html
    ServerName site2.com
    ErrorLog logs/site2-error_log
    CustomLog logs/site2-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>

<VirtualHost *:83>
    ServerAdmin [email protected]
    DocumentRoot /var/www/site3/html
    ServerName site3.com
    ErrorLog logs/site3-error_log
    CustomLog logs/site3-access_log common
    ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>

Restart apache

service httpd restart

You can now refer Site1 :

http://<ip-address>:81/ 
http://<ip-address>:81/cgi-bin/

Site2 :

http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/

Site3 :

http://<ip-address>:83/ 
http://<ip-address>:83/cgi-bin/

If path is not hardcoded in any script then your websites should work seamlessly.

The specified child already has a parent. You must call removeView() on the child's parent first

In my case the problem was I was trying to add same view multiple times to linear layout

View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);

 for (int i = 1; i <= totalCount; i++) {

     parentLayout.addView(childView);

 }

just initialize view every time to fix the issue

 for (int i = 1; i <= totalCount; i++) {

     View childView = LayoutInflater.from(context).inflate(R.layout.lay_progressheader, parentLayout,false);

      parentLayout.addView(childView);

 }

Converting a float to a string without rounding it

I know this is too late but for those who are coming here for the first time, I'd like to post a solution. I have a float value index and a string imgfile and I had the same problem as you. This is how I fixed the issue

index = 1.0
imgfile = 'data/2.jpg'
out = '%.1f,%s' % (index,imgfile)
print out

The output is

1.0,data/2.jpg

You may modify this formatting example as per your convenience.

Excel compare two columns and highlight duplicates

A simple formula to use is

=COUNTIF($B:$B,A1)

Formula specified is for cell A1. Simply copy and paste special - format to the whole of column A

how to instanceof List<MyType>?

You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List

Executing Javascript from Python

You can also use Js2Py which is written in pure python and is able to both execute and translate javascript to python. Supports virtually whole JavaScript even labels, getters, setters and other rarely used features.

import js2py

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")

result = js2py.eval_js(js)  # executing JavaScript and converting the result to python string 

Advantages of Js2Py include portability and extremely easy integration with python (since basically JavaScript is being translated to python).

To install:

pip install js2py

Printing tuple with string formatting in Python

Talk is cheap, show you the code:

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>> 

Visual Studio move project to a different folder

What worked for me was to:

  1. Remove the project from the solution.
  2. Edit the project file with a text editor.
  3. Update all relative paths to the "packages". In my case I had to change ..\packages to ..\..\..\packages since I moved the project to a deeper folder.
  4. Load the project back into the solution.

How do I check if an object has a key in JavaScript?

You should use hasOwnProperty. For example:

myObj.hasOwnProperty('myKey');

Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:

Object.prototype.hasOwnProperty.call(myObj, 'myKey');

Pipe output and capture exit status in Bash

This solution works without using bash specific features or temporary files. Bonus: in the end the exit status is actually an exit status and not some string in a file.

Situation:

someprog | filter

you want the exit status from someprog and the output from filter.

Here is my solution:

((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1

echo $?

See my answer for the same question on unix.stackexchange.com for a detailed explanation and an alternative without subshells and some caveats.

Android Fragment onAttach() deprecated

Currently from the onAttach Fragment code, it is not clear if the Context is the current activity: Source Code

public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

If you will take a look at getActivity you will see the same call

/**
 * Return the Activity this fragment is currently associated with.
 */
final public Activity getActivity() {
    return mHost == null ? null : mHost.getActivity();
}

So If you want to be sure that you are getting the Activity then use getActivity() (in onAttach in your Fragment) but don't forget to check for null because if mHost is null your activity will be null

How to trigger an event in input text after I stop typing/writing?

You need debounce!

Here is a jQuery plugin, and here is all you need to know about debounce. If you are coming here from Google and Underscore has found its way into the JSoup of your app, it has debounce baked right in!

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

ANTLR: Is there a simple example?

ANTLR mega tutorial by Gabriele Tomassetti is very helpful

It has grammar examples, examples of visitors in different languages (Java, JavaScript, C# and Python) and many other things. Highly recommended.

EDIT: other useful articles by Gabriele Tomassetti on ANTLR

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

You can use sticky position. Here is a sample code. This is HTML/CSS solution. No js is required.

_x000D_
_x000D_
.view {
  margin: auto;
  width: 600px;
}

.wrapper {
  position: relative;
  overflow: auto;
  border: 1px solid black;
  white-space: nowrap;
}

.sticky-col {
  position: -webkit-sticky;
  position: sticky;
  background-color: white;
}

.first-col {
  width: 100px;
  min-width: 100px;
  max-width: 100px;
  left: 0px;
}

.second-col {
  width: 150px;
  min-width: 150px;
  max-width: 150px;
  left: 100px;
}
_x000D_
<div class="view">
  <div class="wrapper">
    <table class="table">
      <thead>
        <tr>
          <th class="sticky-col first-col">Number</th>
          <th class="sticky-col second-col">First Name</th>
          <th>Last Name</th>
          <th>Employer</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="sticky-col first-col">1</td>
          <td class="sticky-col second-col">Mark</td>
          <td>Ham</td>
          <td>Micro</td>
        </tr>
        <tr>
          <td class="sticky-col first-col">2</td>
          <td class="sticky-col second-col">Jacob</td>
          <td>Smith</td>
          <td>Adob Adob Adob AdobAdob Adob Adob Adob Adob</td>
        </tr>
        <tr>
          <td class="sticky-col first-col">3</td>
          <td class="sticky-col second-col">Larry</td>
          <td>Wen</td>
          <td>Goog Goog Goog GoogGoog Goog Goog Goog Goog Goog</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Bootply code: https://www.bootply.com/g8pfBXOcY9

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

git push >> fatal: no configured push destination

The command (or the URL in it) to add the github repository as a remote isn't quite correct. If I understand your repository name correctly, it should be;

git remote add demo_app '[email protected]:levelone/demo_app.git'

Update MySQL using HTML Form and PHP

you have error in your sql syntax.

please use this query and checkout.

$query = mysql_query("UPDATE `anstalld` SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ");

Getting reference to the top-most view/window in iOS application

If your application only works in portrait orientation, this is enough:

[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]

And your view will not be shown over keyboard and status bar.

If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:

https://github.com/HarrisonXi/TopmostView

It supports iOS7/8/9.

Python progression path - From apprentice to guru

def apprentice():
  read(diveintopython)
  experiment(interpreter)
  read(python_tutorial)
  experiment(interpreter, modules/files)
  watch(pycon)

def master():
  refer(python-essential-reference)
  refer(PEPs/language reference)
  experiment()
  read(good_python_code) # Eg. twisted, other libraries
  write(basic_library)   # reinvent wheel and compare to existing wheels
  if have_interesting_ideas:
     give_talk(pycon)

def guru():
  pass # Not qualified to comment. Fix the GIL perhaps?

How to set up a Web API controller for multipart/form-data

Perhaps it is late for the party. But there is an alternative solution for this is to use ApiMultipartFormFormatter plugin.

This plugin helps you to receive the multipart/formdata content as ASP.NET Core does.

In the github page, demo is already provided.

Difference between HashSet and HashMap?

HashMap is a Map implementation, allowing duplicate values but not duplicate keys.. For adding an object a Key/Value pair is required. Null Keys and Null values are allowed. eg:

{The->3,world->5,is->2,nice->4}

HashSet is a Set implementation,which does not allow duplicates.If you tried to add a duplicate object, a call to public boolean add(Object o) method, then the set remains unchanged and returns false. eg:

[The,world,is,nice]

How do I call a JavaScript function on page load?

here's the trick (works everywhere):

r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

What is the difference between procedural programming and functional programming?

Procedural programming divides sequences of statements and conditional constructs into separate blocks called procedures that are parameterized over arguments that are (non-functional) values.

Functional programming is the same except that functions are first-class values, so they can be passed as arguments to other functions and returned as results from function calls.

Note that functional programming is a generalization of procedural programming in this interpretation. However, a minority interpret "functional programming" to mean side-effect-free which is quite different but irrelevant for all major functional languages except Haskell.

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

Data access object (DAO) in Java

I am going to be general and not specific to Java as DAO and ORM are used in all languages.

To understand DAO you first need to understand ORM (Object Relational Mapping). This means that if you have a table called "person" with columns "name" and "age", then you would create object-template for that table:

type Person {
name
age
}

Now with help of DAO instead of writing some specific queries, to fetch all persons, for what ever type of db you are using (which can be error-prone) instead you do:

list persons = DAO.getPersons();
...
person = DAO.getPersonWithName("John");
age = person.age;

You do not write the DAO abstraction yourself, instead it is usually part of some opensource project, depending on what language and framework you are using.

Now to the main question here. "..where it is used..". Well usually if you are writing complex business and domain specific code your life will be very difficult without DAO. Of course you do not need to use ORM and DAO provided, instead you can write your own abstraction and native queries. I have done that in the past and almost always regretted it later.

My Routes are Returning a 404, How can I Fix Them?

On my Ubuntu LAMP installation, I solved this problem with the following 2 changes.

  1. Enable mod_rewrite on the apache server: sudo a2enmod rewrite.
  2. Edit /etc/apache2/apache2.conf, changing the "AllowOverride" directive for the /var/www directory (which is my main document root): AllowOverride All

Then restart the Apache server: service apache2 restart

How can I make a ComboBox non-editable in .NET?

COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where d.id in (
    select a.id from docs_documents a
    left join docx_document b on b.id = a.document_id
    where b.id is null
        and floor(sysdate - a.create_date) > 120
 );

Calculating difference between two timestamps in Oracle in milliseconds

When you subtract two variables of type TIMESTAMP, you get an INTERVAL DAY TO SECOND which includes a number of milliseconds and/or microseconds depending on the platform. If the database is running on Windows, systimestamp will generally have milliseconds. If the database is running on Unix, systimestamp will generally have microseconds.

  1  select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' )
  2*   from dual
SQL> /

SYSTIMESTAMP-TO_TIMESTAMP('2012-07-23','YYYY-MM-DD')
---------------------------------------------------------------------------
+000000000 14:51:04.339000000

You can use the EXTRACT function to extract the individual elements of an INTERVAL DAY TO SECOND

SQL> ed
Wrote file afiedt.buf

  1  select extract( day from diff ) days,
  2         extract( hour from diff ) hours,
  3         extract( minute from diff ) minutes,
  4         extract( second from diff ) seconds
  5    from (select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' ) diff
  6*           from dual)
SQL> /

      DAYS      HOURS    MINUTES    SECONDS
---------- ---------- ---------- ----------
         0         14         55     37.936

You can then convert each of those components into milliseconds and add them up

SQL> ed
Wrote file afiedt.buf

  1  select extract( day from diff )*24*60*60*1000 +
  2         extract( hour from diff )*60*60*1000 +
  3         extract( minute from diff )*60*1000 +
  4         round(extract( second from diff )*1000) total_milliseconds
  5    from (select systimestamp - to_timestamp( '2012-07-23', 'yyyy-mm-dd' ) diff
  6*           from dual)
SQL> /

TOTAL_MILLISECONDS
------------------
          53831842

Normally, however, it is more useful to have either the INTERVAL DAY TO SECOND representation or to have separate columns for hours, minutes, seconds, etc. rather than computing the total number of milliseconds between two TIMESTAMP values.

Hiding the R code in Rmarkdown/knit and just showing the results

Might also be interesting for you to know that you can use:

{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)

to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)

Media Player called in state 0, error (-38,0)

enter image description here

above the picture,you can get the right way.

What is IllegalStateException?

public class UserNotFoundException extends Exception {
    public UserNotFoundException(String message) {
        super(message)

How many characters in varchar(max)

From http://msdn.microsoft.com/en-us/library/ms176089.aspx

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.

Generating a PNG with matplotlib when DISPLAY is undefined

When signing into the server to execute the code use this instead:

ssh -X username@servername

the -X will get rid of the no display name and no $DISPLAY environment variable error

:)

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

Besides all above solutions, check if you have the "id" or any custom defined parameter in the DELETE method is matching the route config.

public void Delete(int id)
{
    //some code here
}

If you hit with repeated 405 errors better reset the method signature to default as above and try.

The route config by default will look for id in the URL. So the parameter name id is important here unless you change the route config under the App_Start folder.

You may change the data type of the id though.

For example the method below should work just fine:

public void Delete(string id)
{
    //some code here
}

Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.

DELETE http://{url}/{action}/{id}

Example:

DELETE http://localhost/item/1

Hope it helps.

Resize command prompt through commands

I know, that's a 8 years old question, but that can still happen today.

Powershell ca be used for that. An example is shown here. The shortest command for the cmd is:

powershell -command "&{(get-host).ui.rawui.windowsize=@{width=100;height=55};}"

Set your wanted window size to the width and hight vars. However, this short line has two limitations:

  • Be sure that the window size is not larger than the predefined buffer sizes. Otherwise there occur an error message.
  • Depending on the system, loading and processing of Powershell takes 2...4 seconds. Sometimes this is a long time to wait.

To avoid that, in the command below the buffer size is defined. In addition, the process runs parallel to the other following cmd commands:

start /b powershell -command "&{$w=(get-host).ui.rawui;$w.buffersize=@{width=177;height=999};$w.windowsize=@{width=155;height=55};}"

The width and height values to the buffersize object, here 177 and 999, must be bigger or equal to the window size values.

How to verify element present or visible in selenium 2 (Selenium WebDriver)

You could try something like:

    WebElement rxBtn = driver.findElement(By.className("icon-rx"));
    WebElement otcBtn = driver.findElement(By.className("icon-otc"));
    WebElement herbBtn = driver.findElement(By.className("icon-herb"));

    Assert.assertEquals(true, rxBtn.isDisplayed());
    Assert.assertEquals(true, otcBtn.isDisplayed());
    Assert.assertEquals(true, herbBtn.isDisplayed());

This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert whether or not they are displayed. This is using TestNG Assertions.

How to verify if a file exists in a batch file?

Type IF /? to get help about if, it clearly explains how to use IF EXIST.

To delete a complete tree except some folders, see the answer of this question: Windows batch script to delete everything in a folder except one

Finally copying just means calling COPY and calling another bat file can be done like this:

MYOTHERBATFILE.BAT sync.bat myprogram.ini

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

How should I read a file line-by-line in Python?

Yes,

with open('filename.txt') as fp:
    for line in fp:
        print line

is the way to go.

It is not more verbose. It is more safe.

Sorting objects by property values

With ES6 arrow functions it will be like this:

//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
  { brand: 'Benz', top_speed: 110 },
  { brand: 'Fiat', top_speed: 90 },
  { brand: 'Aston Martin', top_speed: 70 } ]

Array.prototype.sort() can accept a comparator function (here I used arrow notation, but ordinary functions work the same):

let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)

// [ { brand: 'Aston Martin', top_speed: 70 },
//   { brand: 'Benz', top_speed: 110 },
//   { brand: 'Fiat', top_speed: 90 },
//   { brand: 'Porsche', top_speed: 260 } ]

The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:

let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)

//[ { brand: 'Aston Martin', top_speed: 70 },
//  { brand: 'Fiat', top_speed: 90 },
//  { brand: 'Benz', top_speed: 110 },
//  { brand: 'Porsche', top_speed: 260 } ]

If you don't mind mutating the orginal array cars.sort(comparatorFunction) will do the trick.

Can't find file executable in your configured search path for gnc gcc compiler

Just open your setting->compiler and click on the reset defaults and it will start work.

How to remove duplicates from Python list and keep order?

For the string data

 output = []

     def uniq(input):
         if input not in output:
            output.append(input)
 print output     

Find the greatest number in a list of numbers

You can use the inbuilt function max() with multiple arguments:

print max(1, 2, 3)

or a list:

list = [1, 2, 3]
print max(list)

or in fact anything iterable.

How do MySQL indexes work?

In MySQL InnoDB, there are two types of index.

  1. Primary key which is called clustered index. Index key words are stored with real record data in the B+Tree leaf node.

  2. Secondary key which is non clustered index. These index only store primary key's key words along with their own index key words in the B+Tree leaf node. So when searching from secondary index, it will first find its primary key index key words and scan the primary key B+Tree to find the real data records. This will make secondary index slower compared to primary index search. However, if the select columns are all in the secondary index, then no need to look up primary index B+Tree again. This is called covering index.

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Try to use:

pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"

Adding a guideline to the editor in Visual Studio

Without the need to edit any registry keys, the Productivity Power Tools extension (available for all versions of visual studio) provides guideline functionality.

Once installed just right click while in the editor window and choose the add guide line option. Note that the guideline will always be placed on the column where your editing cursor is currently at, regardless of where you right click in the editor window.

enter image description here

To turn off go to options and find Productivity Power Tools and in that section turn off Column Guides. A reboot will be necessary.

enter image description here

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.

As soon as you show a Dialog it throws the error:

Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

You can see its a MessageBox causing the problem in the stack trace:

at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon,  MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)  

Solution

If you're running your app on a Scheduled Task send an email instead of showing a Dialog.

ImportError: No module named enum

Depending on your rights, you need sudo at beginning.

Div side by side without float

Use display:table-cell; for removing space between .Left and .Right

_x000D_
_x000D_
div.left {_x000D_
    background:blue;_x000D_
    height:200px;_x000D_
    width:300px;_x000D_
}_x000D_
_x000D_
div.right{_x000D_
    background:green;_x000D_
    height:300px;_x000D_
    width:100px;_x000D_
}_x000D_
_x000D_
.container{_x000D_
    background:black;_x000D_
    height:400px;_x000D_
    width:450px;_x000D_
}_x000D_
_x000D_
.container > div {_x000D_
    display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>_x000D_
    <div class="left">_x000D_
      LEFT_x000D_
    </div>_x000D_
  </div>_x000D_
  <div>_x000D_
    <div class="right">_x000D_
      RIGHT_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you check for permissions to write to a directory or file?

None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..

/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
    if (string.IsNullOrEmpty(DirectoryPath)) return false;

    try
    {
        AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        WindowsIdentity identity = WindowsIdentity.GetCurrent();

        foreach (FileSystemAccessRule rule in rules)
        {
            if (identity.Groups.Contains(rule.IdentityReference))
            {
                if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
                {
                    if (rule.AccessControlType == AccessControlType.Allow)
                        return true;
                }
            }
        }
    }
    catch {}
    return false;
}

How to "properly" create a custom object in JavaScript?

A Pattern That Serves Me Well
var Klass = function Klass() {
    var thus = this;
    var somePublicVariable = x
      , somePublicVariable2 = x
      ;
    var somePrivateVariable = x
      , somePrivateVariable2 = x
      ;

    var privateMethod = (function p() {...}).bind(this);

    function publicMethod() {...}

    // export precepts
    this.var1 = somePublicVariable;
    this.method = publicMethod;

    return this;
};

First, you may change your preference of adding methods to the instance instead of the constructor's prototype object. I almost always declare methods inside of the constructor because I use Constructor Hijacking very often for purposes regarding Inheritance & Decorators.

Here's how I decide where which declarations are writ:

  • Never declare a method directly on the context object (this)
  • Let var declarations take precedence over function declarations
  • Let primitives take precedence over objects ({} and [])
  • Let public declarations take precedence over private declarations
  • Prefer Function.prototype.bind over thus, self, vm, etc
  • Avoid declaring a Class within another Class, unless:
    • It should be obvious that the two are inseparable
    • The Inner class implements The Command Pattern
    • The Inner class implements The Singleton Pattern
    • The Inner class implements The State Pattern
    • The Inner Class implements another Design Pattern that warrants this
  • Always return this from within the Lexical Scope of the Closure Space.

Here's why these help:

Constructor Hijacking
var Super = function Super() {
    ...
    this.inherited = true;
    ...
};
var Klass = function Klass() {
    ...
    // export precepts
    Super.apply(this);  // extends this with property `inherited`
    ...
};
Model Design
var Model = function Model(options) {
    var options = options || {};

    this.id = options.id || this.id || -1;
    this.string = options.string || this.string || "";
    // ...

    return this;
};
var model = new Model({...});
var updated = Model.call(model, { string: 'modified' });
(model === updated === true);  // > true
Design Patterns
var Singleton = new (function Singleton() {
    var INSTANCE = null;

    return function Klass() {
        ...
        // export precepts
        ...

        if (!INSTANCE) INSTANCE = this;
        return INSTANCE;
    };
})();
var a = new Singleton();
var b = new Singleton();
(a === b === true);  // > true

As you can see, I really have no need for thus since I prefer Function.prototype.bind (or .call or .apply) over thus. In our Singleton class, we don't even name it thus because INSTANCE conveys more information. For Model, we return this so that we can invoke the Constructor using .call to return the instance we passed into it. Redundantly, we assigned it to the variable updated, though it is useful in other scenarios.

Alongside, I prefer constructing object-literals using the new keyword over {brackets}:

Preferred
var klass = new (function Klass(Base) {
    ...
    // export precepts
    Base.apply(this);  //
    this.override = x;
    ...
})(Super);
Not Preferred
var klass = Super.apply({
    override: x
});

As you can see, the latter has no ability to override its Superclass's "override" property.

If I do add methods to the Class's prototype object, I prefer an object literal -- with or without using the new keyword:

Preferred
Klass.prototype = new Super();
// OR
Klass.prototype = new (function Base() {
    ...
    // export precepts
    Base.apply(this);
    ...
})(Super);
// OR
Klass.prototype = Super.apply({...});
// OR
Klass.prototype = {
    method: function m() {...}
};
Not Preferred
Klass.prototype.method = function m() {...};

How to use a App.config file in WPF applications?

You have to reference System.Configuration via explorer (not only append using System.Configuration). Then you can write:

string xmlDataDirectory = 
    System.Configuration.ConfigurationManager.AppSettings.Get("xmlDataDirectory");

Tested with VS2010 (thanks to www.developpez.net). Hope this helps.

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

Java - Access is denied java.io.FileNotFoundException

When you create a new File, you are supposed to provide the file name, not only the directory you want to put your file in.

Try with something like

File file = new File("D:/Data/" + item.getFileName());

Convert nullable bool? to bool

You ultimately have to decide what the null bool will represent. If null should be false, you can do this:

bool newBool = x.HasValue ? x.Value : false;

Or:

bool newBool = x.HasValue && x.Value;

Or:

bool newBool = x ?? false;

Remove special symbols and extra spaces and replace with underscore using the replace method

Remove the \s from your new regex and it should work - whitespace is already included in "anything but alphanumerics".

Note that you may want to add a + after the ] so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'') to trim off underscores at the start or end of the string.

How to find if element with specific id exists or not

You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.

You also have a wrong condition, you're checking

if (myEle == null)

which you should change to

if (myEle != null)

var myEle = document.getElementById("myElement");
if(myEle != null) { 
    var myEleValue= myEle.value; 
}

How to set the height of an input (text) field in CSS?

Form controls are notoriously difficult to style cross-platform/browser. Some browsers will honor a CSS height rule, some won't.

You can try line-height (may need display:block; or display:inline-block;) or top and bottom padding also. If none of those work, that's pretty much it - use a graphic, position the input in the center and set border:none; so it looks like the form control is big but it actually isn't...

Disable XML validation in Eclipse

Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.

So, if I have the following NewFile.xml:

<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />

And the eclipse encoding is UTF-8:

Eclipse Encoding Resource

The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.

The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.

EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.

When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.

  1. Suspend the validators
  2. Click on the 'Content is not allowed in prolog' message, right click and delete. You can select multiple ones, or all of them.
  3. Do a Project->Clean. The messages should not come back.

I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.

Reliable way for a Bash script to get the full path to itself

Considering this issue again: there is a very popular solution that is referenced within this thread that has its origin here:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

I have stayed away from this solution because of the use of dirname - it can present cross-platform difficulties, particularly if a script needs to be locked down for security reasons. But as a pure Bash alternative, how about using:

DIR="$( cd "$( echo "${BASH_SOURCE[0]%/*}" )" && pwd )"

Would this be an option?

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

It's a kludge, but assuming there's a minimum length for SEARCHSTRING, for example 2 characters, substring the SEARCHSTRING parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu") and SEARCHSTRING2 ("ll"). Concatenate them back together when executing the query to the database.

How can I send JSON response in symfony2 controller

Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper

public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));

// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}

Custom UITableViewCell from nib in Swift

Another method that may work for you (it's how I do it) is registering a class.

Assume you create a custom tableView like the following:

class UICustomTableViewCell: UITableViewCell {...}

You can then register this cell in whatever UITableViewController you will be displaying it in with "registerClass":

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.registerClass(UICustomTableViewCell.self, forCellReuseIdentifier: "UICustomTableViewCellIdentifier")
}

And you can call it as you would expect in the cell for row method:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("UICustomTableViewCellIdentifier", forIndexPath: indexPath) as! UICustomTableViewCell
    return cell
}

What is the benefit of zerofill in MySQL?

mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tin3;
+----+------------+
| id | val        |
+----+------------+
|  1 | 0000000012 |
|  2 | 0000000007 |
|  4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)

mysql>

mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
|          10 |
+-------------+
1 row in set (0.01 sec)


mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
|     8 |
+-------+
1 row in set (0.00 sec)

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

Is there possibility of sum of ArrayList without looping

for me the clearest way is this:

doubleList.stream().reduce((a,b)->a+b).get();

or

doubleList.parallelStream().reduce((a,b)->a+b).get();

It also use internal loops, but it is not possible without loops.

How to see the changes between two commits without commits in-between?

Suppose you want to see the difference between commits 012345 and abcdef. The following should do what you want:

$ git checkout 012345
$ git cherry-pick -n abcdef
$ git diff --cached

How can I get Eclipse to show .* files?

If using Zend Studio, same arrow, go to RSE view, click on the downward facing arrow, hit preferences, and then check show hidden files.

That did the trick for me.

403 Forbidden vs 401 Unauthorized HTTP responses

This is simpler in my head than anywhere here, so:

401: You need HTTP basic auth to see this.

403: You can't see this, and HTTP basic auth won't help.

If the user just needs to log in using you site's standard HTML login form, 401 would not be appropriate because it is specific to HTTP basic auth.

I don't recommend using 403 to deny access to things like /includes, because as far as the web is concerned, those resources don't exist at all and should therefore 404.

This leaves 403 as "you need to be logged in".

In other words, 403 means "this resource requires some form of auth other than HTTP basic auth".

https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2

How to Get a Sublist in C#

With LINQ:

List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();

If you need foreach, then no need for ToList:

foreach (string s in l.Skip(1).Take(2)){}

Advantage of LINQ is that if you want to just skip some leading element,you can :

List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}

i.e. no need to take care of count/length, etc.

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

Difference Between ViewResult() and ActionResult()

ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

Using sed to split a string with a delimiter

Using simply :

$ tr ':' $'\n' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

If you really need :

$ sed 's/:/\n/g' <<< string1:string2:string3:string4:string5
string1
string2
string3
string4
string5

How to select data of a table from another database in SQL Server?

You need sp_addlinkedserver()

http://msdn.microsoft.com/en-us/library/ms190479.aspx

Example:

exec sp_addlinkedserver @server = 'test'

then

select * from [server].[database].[schema].[table]

In your example:

select * from [test].[testdb].[dbo].[table]

How to make a DIV not wrap?

Try using white-space: nowrap; in the container style (instead of overflow: hidden;)

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

Python read next()

Using next or readlines etc, is not necessary. As the documentation says: "For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code".

Here's an example:

with open('/path/to/file') as myfile:
    for line in myfile:
        print(line)

How to use multiprocessing pool.map with multiple arguments?

This might be another option. The trick is in the wrapper function that returns another function which is passed in to pool.map. The code below reads an input array and for each (unique) element in it, returns how many times (ie counts) that element appears in the array, For example if the input is

np.eye(3) = [ [1. 0. 0.]
              [0. 1. 0.]
              [0. 0. 1.]]

then zero appears 6 times and one 3 times

import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count


def extract_counts(label_array):
    labels = np.unique(label_array)
    out = extract_counts_helper([label_array], labels)
    return out

def extract_counts_helper(args, labels):
    n = max(1, cpu_count() - 1)
    pool = ThreadPool(n)
    results = {}
    pool.map(wrapper(args, results), labels)
    pool.close()
    pool.join()
    return results

def wrapper(argsin, results):
    def inner_fun(label):
        label_array = argsin[0]
        counts = get_label_counts(label_array, label)
        results[label] = counts
    return inner_fun

def get_label_counts(label_array, label):
    return sum(label_array.flatten() == label)

if __name__ == "__main__":
    img = np.ones([2,2])
    out = extract_counts(img)
    print('input array: \n', img)
    print('label counts: ', out)
    print("========")
           
    img = np.eye(3)
    out = extract_counts(img)
    print('input array: \n', img)
    print('label counts: ', out)
    print("========")
    
    img = np.random.randint(5, size=(3, 3))
    out = extract_counts(img)
    print('input array: \n', img)
    print('label counts: ', out)
    print("========")

You should get:

input array: 
 [[1. 1.]
 [1. 1.]]
label counts:  {1.0: 4}
========
input array: 
 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
label counts:  {0.0: 6, 1.0: 3}
========
input array: 
 [[4 4 0]
 [2 4 3]
 [2 3 1]]
label counts:  {0: 1, 1: 1, 2: 2, 3: 2, 4: 3}
========

How can I make a time delay in Python?

If you would like to put a time delay in a Python script:

Use time.sleep or Event().wait like this:

from threading import Event
from time import sleep

delay_in_sec = 2

# Use time.sleep like this
sleep(delay_in_sec)         # Returns None
print(f'slept for {delay_in_sec} seconds')

# Or use Event().wait like this
Event().wait(delay_in_sec)  # Returns False
print(f'waited for {delay_in_sec} seconds')

However, if you want to delay the execution of a function do this:

Use threading.Timer like this:

from threading import Timer

delay_in_sec = 2

def hello(delay_in_sec):
    print(f'function called after {delay_in_sec} seconds')

t = Timer(delay_in_sec, hello, [delay_in_sec])  # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start()  # Returns None
print("Started")

Outputs:

Started
function called after 2 seconds

Why use the later approach?

  • It does not stop execution of the whole script (except for the function you pass it).
  • After starting the timer you can also stop it by doing timer_obj.cancel().

How to declare a static const char* in your header file?

There is a trick you can use with templates to provide H file only constants.

(note, this is an ugly example, but works verbatim in at least in g++ 4.6.1.)

(values.hpp file)

#include <string>

template<int dummy>
class tValues
{
public:
   static const char* myValue;
};

template <int dummy> const char* tValues<dummy>::myValue = "This is a value";

typedef tValues<0> Values;

std::string otherCompUnit(); // test from other compilation unit

(main.cpp)

#include <iostream>
#include "values.hpp"

int main()
{
   std::cout << "from main: " << Values::myValue << std::endl;
   std::cout << "from other: " << otherCompUnit() << std::endl;
}

(other.cpp)

#include "values.hpp"

std::string otherCompUnit () {
   return std::string(Values::myValue);
}

Compile (e.g. g++ -o main main.cpp other.cpp && ./main) and see two compilation units referencing the same constant declared in a header:

from main: This is a value
from other: This is a value

In MSVC, you may instead be able to use __declspec(selectany)

For example:

__declspec(selectany) const char* data = "My data";

How To: Execute command line in C#, get STD OUT results

Julian's solution is tested working with some minor corrections. The following is an example that also used https://sourceforge.net/projects/bat-to-exe/ GenericConsole.cs and https://www.codeproject.com/Articles/19225/Bat-file-compiler program.txt for args part:

using System;
using System.Text;  //StringBuilder
using System.Diagnostics;
using System.IO;


class Program
{
    private static bool redirectStandardOutput = true;

    private static string buildargument(string[] args)
    {
        StringBuilder arg = new StringBuilder();
        for (int i = 0; i < args.Length; i++)
        {
            arg.Append("\"" + args[i] + "\" ");
        }

        return arg.ToString();
    }

    static void Main(string[] args)
    {
        Process prc = new Process();
        prc.StartInfo = //new ProcessStartInfo("cmd.exe", String.Format("/c \"\"{0}\" {1}", Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args)));
        //new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args));
        new ProcessStartInfo("mapTargetIDToTargetNameA3.bat");
        prc.StartInfo.Arguments = buildargument(args);

        prc.EnableRaisingEvents = true;

        if (redirectStandardOutput == true)
        {
            prc.StartInfo.UseShellExecute = false;
        }
        else
        {
            prc.StartInfo.UseShellExecute = true;
        }

        prc.StartInfo.CreateNoWindow = true;

        prc.OutputDataReceived += OnOutputDataRecived;
        prc.ErrorDataReceived += OnErrorDataReceived;
        //prc.Exited += OnExited;

        prc.StartInfo.RedirectStandardOutput = redirectStandardOutput;
        prc.StartInfo.RedirectStandardError = redirectStandardOutput;

        try
        {
            prc.Start();
            prc.BeginOutputReadLine();
            prc.BeginErrorReadLine();
            prc.WaitForExit();
        }
        catch (Exception e)
        {
            Console.WriteLine("OS error: " + e.Message);
        }

        prc.Close();
    }

    // Handle the dataevent
    private static void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
    {
        //do something with your data
        Console.WriteLine(e.Data);
    }

    //Handle the error
    private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(e.Data);
    }

    // Handle Exited event and display process information.
    //private static void OnExited(object sender, System.EventArgs e)
    //{
    //    var process = sender as Process;
    //    if (process != null)
    //    {
    //        Console.WriteLine("ExitCode: " + process.ExitCode);
    //    }
    //    else
    //    {
    //        Console.WriteLine("Process exited");
    //    }
    //}
}

The code need to compile inside VS2007, using commandline csc.exe generated executable will not show console output correctly, or even crash with CLR20r3 error. Comment out the OnExited event process, the console output of the bat to exe will be more like the original bat console output.

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

CSS vertical-align: text-bottom;

Sometimes you can play with padding and margin top, add line-height, etc.

See fiddle.

Style and text forked from @aspirinemaga

.parent
{
    width:300px;
    line-height:30px;
    border:1px solid red;
    padding-top:20px;
}

Java - using System.getProperty("user.dir") to get the home directory

way of getting home directory of current user is

String currentUsersHomeDir = System.getProperty("user.home");

and to append path separator

String otherFolder = currentUsersHomeDir + File.separator + "other";

File.separator

The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.

A variable modified inside a while loop is not remembered

How about a very simple method

    +call your while loop in a function 
     - set your value inside (nonsense, but shows the example)
     - return your value inside 
    +capture your value outside
    +set outside
    +display outside


    #!/bin/bash
    # set -e
    # set -u
    # No idea why you need this, not using here

    foo=0
    bar="hello"

    if [[ "$bar" == "hello" ]]
    then
        foo=1
        echo "Setting  \$foo to $foo"
    fi

    echo "Variable \$foo after if statement: $foo"

    lines="first line\nsecond line\nthird line"

    function my_while_loop
    {

    echo -e $lines | while read line
    do
        if [[ "$line" == "second line" ]]
        then
        foo=2; return 2;
        echo "Variable \$foo updated to $foo inside if inside while loop"
        fi

        echo -e $lines | while read line
do
    if [[ "$line" == "second line" ]]
    then
    foo=2;          
    echo "Variable \$foo updated to $foo inside if inside while loop"
    return 2;
    fi

    # Code below won't be executed since we returned from function in 'if' statement
    # We aready reported the $foo var beint set to 2 anyway
    echo "Value of \$foo in while loop body: $foo"

done
}

    my_while_loop; foo="$?"

    echo "Variable \$foo after while loop: $foo"


    Output:
    Setting  $foo 1
    Variable $foo after if statement: 1
    Value of $foo in while loop body: 1
    Variable $foo after while loop: 2

    bash --version

    GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
    Copyright (C) 2007 Free Software Foundation, Inc.

PostgreSQL: how to convert from Unix epoch to date?

select to_timestamp(cast(epoch_ms/1000 as bigint))::date

worked for me

Which mime type should I use for mp3

You should always use audio/mpeg, because firefox cannot play audio/mpeg3 files

Android studio doesn't list my phone under "Choose Device"

French screenshot

I hope it will help, it did the trick for me, first, after connected my device to the computer I switch the paramater above to "camera device (PTP)"; then, I install PdaNet on my computer, finally all the usb driver were installed, and it works.
My smartphone is a samsung GS2, Android 4.4.2.

How do I add a user when I'm using Alpine as a base image?

The commands are adduser and addgroup.

Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):

ENV USER=docker
ENV UID=12345
ENV GID=23456

RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "$(pwd)" \
    --ingroup "$USER" \
    --no-create-home \
    --uid "$UID" \
    "$USER"

Note the following:

  • --disabled-password prevents prompt for a password
  • --gecos "" circumvents the prompt for "Full Name" etc. on Debian-based systems
  • --home "$(pwd)" sets the user's home to the WORKDIR. You may not want this.
  • --no-create-home prevents cruft getting copied into the directory from /etc/skel

The usage description for these applications is missing the long flags present in the code for adduser and addgroup.

The following long-form flags should work both in alpine as well as debian-derivatives:

adduser

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        --home DIR           Home directory
        --gecos GECOS        GECOS field
        --shell SHELL        Login shell
        --ingroup GRP        Group (by name)
        --system             Create a system user
        --disabled-password  Don't assign a password
        --no-create-home     Don't create home directory
        --uid UID            User id

One thing to note is that if --ingroup isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.

addgroup

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: addgroup [-g GID] [-S] [USER] GROUP

Add a group or add a user to a group

        --gid GID  Group id
        --system   Create a system group

I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.

My entrypoint helper script can be found on GitHub.

The intent is to prepend that script as the first argument to ENTRYPOINT which should cause Docker to infer UID and GID from a relevant bind mount.

An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.

(At the time of writing I don't have documentation for my script. It's still on the todo list!!)

for each loop in groovy

Your code works fine.

def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]

for (objKey in tmpHM.keySet()) {   
    HashMap objHM = (HashMap) list.get(objKey);
    print("objHM: ${objHM}  , ")
}

prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,

See https://groovyconsole.appspot.com/script/5135817529884672

Then click "edit in console", "execute script"

Option to ignore case with .contains method?

In Java 8 you can use the Stream interface:

return dvdList.stream().anyMatch(d -> d.getTitle().equalsIgnoreCase("SomeTitle"));

How to delete a cookie using jQuery?

You can also delete cookies without using jquery.cookie plugin:

document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';

How to install an APK file on an Android phone?

Put the APK file into the tools folder in the Android SDK and give the path to tools in the command prompt and use the command:

adb install "name".apk file

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789

Highlight the difference between two strings in PHP

If you want a robust library, Text_Diff (a PEAR package) looks to be pretty good. It has some pretty cool features.

How do I get the current date and time in PHP?

For the new PHP programmer might confuse why there are lot of method for to get current date and time and which one to use in their project.

1. date method (PHP 4, PHP 5, PHP 7)

This is the very common and very easiest way to get the date and time in php.

// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));

You can learn more about it in here

2. DateTime class (PHP 5 >= 5.2.0, PHP 7)

when you want to use PHP with OOP, this is the best way to get date and time.

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

You can learn more about it in here

3. Carbon Date time package

if you are using Composer, Laravel, Symfony or any kinda framework this is the best way to get the date and time. Also this package extends DateTime class in php so you use all the method in Datetime class. This in-built in frameworks like laravel so you don't have to install it separately.

printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // automatically converted to string
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

// Carbon embed 823 languages:
echo $tomorrow->locale('fr')->isoFormat('dddd, MMMM Do YYYY, h:mm');
echo $tomorrow->locale('ar')->isoFormat('dddd, MMMM Do YYYY, h:mm');

$officialDate = Carbon::now()->toRfc2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');

if (Carbon::now()->isWeekend()) {
    echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'

You can learn more about it in here

Hope this helps and if you know any other way to get the date and time feel free to edit the answer.

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

Match the .env file and the config.php file with your username and password and your hostname in the database settings.if they are not equal,relation will not connect.

Is there a decorator to simply cache function return values?

functools.cache is released in Python 3.9 (docs):

from functools import cache

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

In previous versions, one of the early answers is still a valid solution using lru_cache as an ordinary cache without limit and lru feature. (docs)

If maxsize is set to None, the LRU feature is disabled and the cache can grow without bound.

Here is a prettier version of it:

cache = lru_cache(maxsize=None)

@cache
def func(param1):
   pass

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

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

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

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

How do I create a comma delimited string from an ArrayList?

The solutions so far are all quite complicated. The idiomatic solution should doubtless be:

String.Join(",", x.Cast(Of String)().ToArray())

There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:

Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String())))

mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf keyword. Also, Convert.ToString is rather inefficient (lots of unnecessary internal evaluations) and the Convert class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.

Thymeleaf: Concatenation - Could not parse as expression


We can concat Like this :


<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>

SQL: Alias Column Name for Use in CASE Statement

@OMG Ponies - One of my reasons of not using the following code

SELECT t.col1 as a, 
     CASE WHEN t.col1 = 'test' THEN 'yes' END as value 
FROM TABLE t;

can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like

Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)') 
as XMLTagAlias from Table

how to change listen port from default 7001 to something different?

I solved the issue by Changing the port no. in adrs-instances.xml file:

\JDEV_USER_HOME\system11.1.1.3.37.56.60\o.j2ee\adrs-instances.xml

Pinging an IP address using PHP and echoing the result

NOTE: Solution below does not work on Windows. On linux exec a "which ping" command from the console, and set command path (of the suggested exec call) accordingly

I think you want to check the exit status of the command, whereas shell_exec gives you full output (might be dangerous shall command output change from command version to version. for some reason). Moreover your variable $ip is not interpreted within single quotes. You'd have to use double ones "". That might be the only thing you need to fix in order to make it work.

But I think following code can be more "portable". IMHO it is in fact better to catch the exit status, rather than trying to parse result string. IMHO it's also better to specify full path to ping command.

<?php
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -n 3 $ip", $outcome, $status);
    if (0 == $status) {
        $status = "alive";
    } else {
        $status = "dead";
    }
    echo "The IP address, $ip, is  ".$status;
}

pingAddress("127.0.0.1");

Difference of two date time in sql server

SELECT DATEDIFF (MyUnits, '2010-01-22 15:29:55.090', '2010-01-22 15:30:09.153')

Substitute "MyUnits" based on DATEDIFF on MSDN

How to inspect Javascript Objects

Use your console:

console.log(object);

Or if you are inspecting html dom elements use console.dir(object). Example:

let element = document.getElementById('alertBoxContainer');
console.dir(element);

Or if you have an array of js objects you could use:

console.table(objectArr);

If you are outputting a lot of console.log(objects) you can also write

console.log({ objectName1 });
console.log({ objectName2 });

This will help you label the objects written to console.

zsh compinit: insecure directories

  1. run compaudit and it will give you a list of directories it thinks are insecure

  2. sudo chown -R username:root target_directory

  3. sudo chmod -R 755 target_directory

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Swift 3 & Xcode 8.3.2

This code will help you, i add an explanation too

// Create custom class, this will make your life easier
class CustomDelay {

    static let cd = CustomDelay()

    // This is your custom delay function
    func runAfterDelay(_ delay:Double, closure:@escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}


// here how to use it (Example 1)
class YourViewController: UIViewController {

    // example delay time 2 second
    let delayTime = 2.0

    override func viewDidLoad() {
        super.viewDidLoad()

        CustomDelay.cd.runAfterDelay(delayTime) {
            // This func will run after 2 second
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
            self.runFunc()
        }
    }

    // example function 1
    func runFunc() {
        // do your method 1 here
    }
}

// here how to use it (Example 2)
class YourSecondViewController: UIViewController {

    // let say you want to user run function shoot after 3 second they tap a button

    // Create a button (This is programatically, you can create with storyboard too)
    let shootButton: UIButton = {
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 15, y: 15, width: 40, height: 40) // Customize where do you want to put your button inside your ui
        button.setTitle("Shoot", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // create an action selector when user tap shoot button
        shootButton.addTarget(self, action: #selector(shoot), for: .touchUpInside)   
    }

    // example shoot function
    func shoot() {
        // example delay time 3 second then shoot
        let delayTime = 3.0

        // delay a shoot after 3 second
        CustomDelay.cd.runAfterDelay(delayTime) {
            // your shoot method here
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
        }
    }   
}

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

How do I print my Java object without getting "SomeType@2f92e0f4"?

If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is

    public String toString() {
       return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.

Method to find string inside of the text file. Then getting the following lines up to a certain limit

I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.

This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.

ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
    //Add the path to the list of file paths
    textFilePaths.push_back(path);
    int lineNumber = 1;
    while(!txtFile.eof())
    {
        txtFile.getline(line, 200);
        Line * ln = new Line(line, path, lineNumber);
        lineNumber++;
        myList.push_back(ln);
        vector<string> words = lineParser(ln);
        for(unsigned int i = 0; i < words.size(); i++)
        {
            index->addWord(words[i], ln);
        }
    }
    result = true;
}

Make footer stick to bottom of page correctly

This should help you.

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
    height: 155px;
}

C#: Printing all properties of an object

You can use the TypeDescriptor class to do this:

foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
    string name=descriptor.Name;
    object value=descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}",name,value);
}

TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.

How to input automatically when running a shell over SSH?

Also you can pipe the answers to the script:

printf "y\npassword\n" | sh test.sh

where \n is escape-sequence

Force div element to stay in same place, when page is scrolled

You can do this replacing position:absolute; by position:fixed;.

Open popup and refresh parent page on close popup

You can use the below code in the parent page.

<script>
    window.onunload = refreshParent;
    function refreshParent() {
      window.opener.location.reload();
    }
</script>

Can You Get A Users Local LAN IP Address Via JavaScript?

You can find more info about what limitations browsers will likely add to mitigate this and what IETF is doing about it as well as why this is needed at IETF SPEC on IP handling

Regular Expressions- Match Anything

I recommend use /(?=.*...)/g

Example

const text1 = 'I am using regex';
/(?=.*regex)/g.test(text1) // true

const text2 = 'regex is awesome';
/(?=.*regex)/g.test(text2) // true

const text3 = 'regex is util';
/(?=.*util)(?=.*regex)/g.test(text3) // true

const text4 = 'util is necessary';
/(?=.*util)(?=.*regex)/g.test(text4) // false because need regex in text

Use regex101 to test

React - Preventing Form Submission

There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.

To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.

JSON formatter in C#?

There are already a bunch of great answers here that use Newtonsoft.JSON, but here's one more that uses JObject.Parse in combination with ToString(), since that hasn't been mentioned yet:

var jObj = Newtonsoft.Json.Linq.JObject.Parse(json);
var formatted = jObj.ToString(Newtonsoft.Json.Formatting.Indented);

SQL Query Where Date = Today Minus 7 Days

Using dateadd to remove a week from the current date.

datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()

Android Studio doesn't recognize my device

Did you try to configure the "Media Mode" in "Camera (PTP)" instead of "Media device (MTP)"? This is sometimes solving the issue. Its in the USB Computer Connection options of your Android device, you should see an "authorize" dialog then.

Update 04/2017: looks like it has been fixed in Android 7.1.2

Regular expression for a hexadecimal number?

Not a big deal, but most regex engines support the POSIX character classes, and there's [:xdigit:] for matching hex characters, which is simpler than the common 0-9a-fA-F stuff.

So, the regex as requested (ie. with optional 0x) is: /(0x)?[[:xdigit:]]+/

set serveroutput on in oracle procedure

Procedure successful but any outpout

Error line1: Unexpected identifier

Here is the code:

SET SERVEROUTPUT ON 

DECLARE

    -- Curseurs 
    CURSOR c1 IS        
    SELECT RWID FROM J_EVT
     WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));

    -- Collections 

    TYPE tc1 IS TABLE OF c1%RWTYPE;

    -- Variables de type record
    rtc1                        tc1;    

    vCpt                        NUMBER:=0;

BEGIN

    OPEN c1;
    LOOP
        FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;

        FORALL i IN 1..rtc1.COUNT 
        DELETE FROM J_EVT
          WHERE RWID = rtc1(i).RWID;
        COMMIT;

        -- Nombres lus : 5025651
        FOR i IN 1..rtc1.COUNT LOOP               
            vCpt := vCpt + SQL%BULK_RWCOUNT(i);
        END LOOP;            

        EXIT WHEN c1%NOTFOUND;   
    END LOOP;
    CLOSE c1;
    COMMIT;

    DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt)); 

END;
/
exit

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

python: get directory two levels up

More cross-platform implementation will be:

import pathlib
two_up = (pathlib.Path(__file__) / ".." / "..").resolve()

Using parent is not supported on Windows. Also need to add .resolve(), to:

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows)

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

To find all socket files on your system run:

sudo find / -type s

My Mysql server system had the socket open at /var/lib/mysql/mysql.sock

Once you find where the socket is being opened, add or edit the line to your /etc/my.cnf file with the path to the socket file:

socket=/var/lib/mysql/mysql.sock

Sometimes the system startup script that launched the command line executable specifies a flag --socket=path. This flag could override the my.cnf location, and that would result in a socket not being found where the my.cnf file indicates it should be. Then when you try to run the mysql command line client, it will read my.cnf to find the socket, but it will not find it since it deviates from where the server created one. So, Unless you care where the socket resides, just changing the my.cnf to match should work.

Then, stop the mysqld process. How you do this will vary by system.

If you're super user in the linux system, try one of the following if you don't know the specific method your Mysql setup uses:

  • service mysqld stop
  • /etc/init.d/mysqld stop
  • mysqladmin -u root -p shutdown
  • Some systems aren't setup to have an elegant way to stop mysql (or for some reason mysql doesn't respond) and you can force terminate mysql with either:
    • One step: pkill -9 mysqld
    • Two step (least preferred):
      • Find the process id of mysql with either pgrep mysql or ps aux | grep mysql | grep -v grep
      • Assuming the process id is 4969 terminate with kill -9 4969

After you do this you might want to look for a pid file in /var/run/mysqld/ and delete it

Make sure the permissions on your socket is such that whatever user mysqld is running as can read/write to it. An easy test is to open it up to full read/write and see if it still works:

chmod 777 /var/run/mysqld/mysqld.sock

If that fixes the issue, you can tailor the permissions and ownership of the socket as needed based on your security settings.

Also, the directory the socket resides in has to be reachable by the user running the mysqld process.

Java collections convert a string to a list of characters

Use a Java 8 Stream.

myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());

Breakdown:

myString
    .chars() // Convert to an IntStream
    .mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
    .collect(Collectors.toList()); // Collect in a List<Character>

(I have absolutely no idea why String#chars() returns an IntStream.)

How to Update/Drop a Hive Partition?

You may also need to make database containing table active

use [dbname]

otherwise you may get error (even if you specify database i.e. dbname.table )

FAILED Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to alter partition. Unable to alter partitions because table or database does not exist.

Checking from shell script if a directory contains files

DIR="/some/dir"
if [ "$(ls -A $DIR)" ]; then
     echo 'There is something alive in here'
fi

How do I determine scrollHeight?

You can also use:

$('#test').context.scrollHeight

Visual Studio opens the default browser instead of Internet Explorer

Right-click on an aspx file and choose 'browse with'. I think there's an option there to set as default.

How to reload the datatable(jquery) data?

You could use this function:

function RefreshTable(tableId, urlData)
    {
      //Retrieve the new data with $.getJSON. You could use it ajax too
      $.getJSON(urlData, null, function( json )
      {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i=0; i<json.aaData.length; i++)
        {
          table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
      });
    }

Dont' forget to call it after your delete function has succeded.

Source: http://www.meadow.se/wordpress/?p=536

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

With Visual Studio 2019 I had a similar issue when I wanted to run tests (MSTest directly from VS). In my case I only had an x64 native DLL and I received this error message. First, I thought it is because Visual Studio runs as x86 but this page helped me to solve the issue:

Run unit test as a 64-bit process

It says

  1. Set your projects to Any CPU
  2. Explicitly define processor architecture

I did both (I explicitly set x64) and then my tests started to work.

Set processor architecture explicitly to x64