Programs & Examples On #Gh unit

GHUnit is a test framework for Objective-C, Mac OS X 10.5 and above and iPhone 3.x and above. It can be used standalone or with other testing frameworks like SenTestingKit or GTM.

Ternary operator (?:) in Bash

(ping -c1 localhost&>/dev/null) && { echo "true"; } || {  echo "false"; }

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Disable Chrome strict MIME type checking

Another solution when a file pretends another extension

I use php inside of var.js file with this .htaccess.

<Files var.js>
    AddType application/x-httpd-php .js
</Files>

Then I write php code in the .js file

<?php
// This is a `.js` file but works with php
echo "var js_variable = '$php_variable';";

When I got the MIME type warning on Chrome, I fixed it by adding a Content-Type header line in the .js(but php) file.

<?php
header('Content-Type: application/javascript');        // <- Add this line
// This is a `.js` file but works with php
...

A browser won't execute .js file because apache sends the Content-Type header of the file as application/x-httpd-php that is defined in .htaccess. That's a security reason. But apache won't execute php as far as htaccess commands the impersonation, it's necessary. So we need to overwrite apache's Content-Type header with the php function header(). I guess that apache stops sending its own header when php sends it instead of apache before.

Difference between r+ and w+ in fopen()

w+

#include <stdio.h>
int main()
{
   FILE *fp;
   fp = fopen("test.txt", "w+");  //write and read mode
   fprintf(fp, "This is testing for fprintf...\n"); 

   rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
   char ch;
   while((ch=getc(fp))!=EOF)
   putchar(ch);

   fclose(fp);
}  

output

This is testing for fprintf...

test.txt

This is testing for fprintf...

w and r to form w+

#include <stdio.h>
int main()
{
   FILE *fp;

   fp = fopen("test.txt", "w"); //only write mode
   fprintf(fp, "This is testing for fprintf...\n"); 
   fclose(fp);
   fp = fopen("test.txt", "r");
   char ch;
   while((ch=getc(fp))!=EOF)
   putchar(ch);
   fclose(fp);
}  

output

This is testing for fprintf...

test.txt

This is testing for fprintf...

r+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "r+");  //read and write mode
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf again...

r and w to form r+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "r"); 
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    fclose(fp);

    fp=fopen("test.txt","w");
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf again...

a+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "a+");  //append and read mode
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf...
This is testing for fprintf again...

a and r to form a+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "a");  //append and read mode
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    fclose(fp);
    fp=fopen("test.txt","r");
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf...
This is testing for fprintf again...

invalid_grant trying to get oAuth token from google

Solved by removing all Authorized redirect URIs in Google console for the project. I use server side flow when you use 'postmessage' as redirect URI

Datetime in where clause

You don't say which database you are using but in MS SQL Server it would be

WHERE DateField = {d '2008-12-20'}

If it is a timestamp field then you'll need a range:

WHERE DateField BETWEEN {ts '2008-12-20 00:00:00'} AND {ts '2008-12-20 23:59:59'}

convert json ipython notebook(.ipynb) to .py file

Jupytext allows for such a conversion on the command line, and importantly you can go back again from the script to a notebook (even an executed notebook). See here.

CASE in WHERE, SQL Server

.. ELSE a.Country ...

I suppose

How to make CREATE OR REPLACE VIEW work in SQL Server?

Edit: Although this question has been marked as a duplicate, it has still been getting attention. The answer provided by @JaKXz is correct and should be the accepted answer.


You'll need to check for the existence of the view. Then do a CREATE VIEW or ALTER VIEW depending on the result.

IF OBJECT_ID('dbo.data_VVVV') IS NULL
BEGIN
    CREATE VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END
ELSE
    ALTER VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
BEGIN
END

How to properly set Column Width upon creating Excel file? (Column properties)

See this snippet: (C#)

    private Microsoft.Office.Interop.Excel.Application xla;
    Workbook wb;
    Worksheet ws;
    Range rg;
    ..........

        xla = new Microsoft.Office.Interop.Excel.Application();
        wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
        ws = (Worksheet)xla.ActiveSheet;
        rg = (Range)ws.Cells[1, 2];
        rg.ColumnWidth = 10;
        rg.Value2 = "Frequency";
        rg = (Range)ws.Cells[1, 3];
        rg.ColumnWidth = 15;
        rg.Value2 = "Impudence";
        rg = (Range)ws.Cells[1, 4];
        rg.ColumnWidth = 8;
        rg.Value2 = "Phase";

Print an integer in binary format in Java

Old school:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));

How to click a browser button with JavaScript automatically?

setInterval(function () {document.getElementById("myButtonId").click();}, 1000);

How to install a Notepad++ plugin offline?

My frustration in being unable to get a plugin for Notepad++ to work came from not realizing that the DLL for the plugin had to be installed directly in the C:\Program Files (x86)\Notepad++\plugins directory, and NOT into a subfolder below that, named for the plugin.

I was misled because every OTHER plugin that comes with the clean installation of Notepad++ IS installed in its own subfolder under \plugins.

\plugins
   + DSpellCheck
   + MIME Tools
   + Converter (etc.)

I tried that with the plugin I was attempting to install (autosave), and just couldn't get it to work. But then thanks to an answer from Steve Chambers above, I tried putting the DLL directly into the \plugins folder and PRESTO! It Works.

Hope this helps save someone else similar frustrations!

SQL distinct for 2 fields in a database

If you still want to group only by one column (as I wanted) you can nest the query:

select c1, count(*) from (select distinct c1, c2 from t) group by c1

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

ASP.Net MVC Redirect To A Different View

Here's what you can do:

return View("another view name", anotherviewmodel);

How to call a parent method from child class in javascript?

How about something based on Douglas Crockford idea:

    function Shape(){}

    Shape.prototype.name = 'Shape';

    Shape.prototype.toString = function(){
        return this.constructor.parent
            ? this.constructor.parent.toString() + ',' + this.name
            : this.name;
    };


    function TwoDShape(){}

    var F = function(){};

    F.prototype = Shape.prototype;

    TwoDShape.prototype = new F();

    TwoDShape.prototype.constructor = TwoDShape;

    TwoDShape.parent = Shape.prototype;

    TwoDShape.prototype.name = '2D Shape';


    var my = new TwoDShape();

    console.log(my.toString()); ===> Shape,2D Shape

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

rails bundle clean

Just remove the obsolete gems from your Gemfile. If you're talking about Heroku (you didn't mention that) then the slug is compiled each new release, just using the current contents of that file.

How to resolve ORA 00936 Missing Expression Error?

update INC.PROV_CSP_DEMO_ADDR_TEMP pd 
set pd.practice_name = (
    select PRSQ_COMMENT FROM INC.CMC_PRSQ_SITE_QA PRSQ
    WHERE PRSQ.PRSQ_MCTR_ITEM = 'PRNM' 
    AND PRSQ.PRAD_ID = pd.provider_id
    AND PRSQ.PRAD_TYPE = pd.prov_addr_type
    AND ROWNUM = 1
)

The most efficient way to implement an integer based power function pow(int, int)

I use recursive, if the exp is even,5^10 =25^5.

int pow(float base,float exp){
   if (exp==0)return 1;
   else if(exp>0&&exp%2==0){
      return pow(base*base,exp/2);
   }else if (exp>0&&exp%2!=0){
      return base*pow(base,exp-1);
   }
}

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

Actionbar notification count icon (badge) like Google has

I found better way to do it. if you want to use something like this

enter image description here

Use this dependency

   compile 'com.nex3z:notification-badge:0.1.0'

create one xml file in drawable and Save it as Badge.xml

<?xml version="1.0" encoding="utf-8"?>
  <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <shape android:shape="oval">
        <solid android:color="#66000000"/>
        <size android:width="30dp" android:height="40dp"/>
    </shape>
</item>
<item android:bottom="1dp" android:right="0.6dp">
    <shape android:shape="oval">
        <solid android:color="@color/Error_color"/>
        <size android:width="20dp" android:height="20dp"/>
    </shape>
</item>
</layer-list>

Now wherever you want to use that badge use following code in xml. with the help of this you will be able to see that badge on top-right corner of your image or anything.

  <com.nex3z.notificationbadge.NotificationBadge
    android:id="@+id/badge"
    android:layout_toRightOf="@id/Your_ICON/IMAGE"
    android:layout_alignTop="@id/Your_ICON/IMAGE"
    android:layout_marginLeft="-16dp"
    android:layout_marginTop="-8dp"
    android:layout_width="28dp"
    android:layout_height="28dp"
    app:badgeBackground="@drawable/Badge"
    app:maxTextLength="2"
    ></com.nex3z.notificationbadge.NotificationBadge>

Now finally on yourFile.java use this 2 simple thing.. 1) Define

 NotificationBadge mBadge;

2) where your loop or anything which is counting this number use this:

 mBadge.setNumber(your_LoopCount);

here, mBadge.setNumber(0) will not show anything.

Hope this help.

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

ConcurrentModificationException for ArrayList

Like the other answers say, you can't remove an item from a collection you're iterating over. You can get around this by explicitly using an Iterator and removing the item there.

Iterator<Item> iter = list.iterator();
while(iter.hasNext()) {
  Item blah = iter.next();
  if(...) {
    iter.remove(); // Removes the 'current' item
  }
}

RegEx match open tags except XHTML self-contained tags

I think the flaw here is that HTML is a Chomsky Type 2 grammar (context free grammar) and a regular expression is a Chomsky Type 3 grammar (regular grammar). Since a Type 2 grammar is fundamentally more complex than a Type 3 grammar (see the Chomsky hierarchy), it is mathematically impossible to parse XML with a regular expression.

But many will try, and some will even claim success - but until others find the fault and totally mess you up.

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

Java get month string from integer

Try:

import java.text.DateFormatSymbols;
monthString = new DateFormatSymbols().getMonths()[month-1];

Alternatively, you could use SimpleDateFormat:

import java.text.SimpleDateFormat;
System.out.println(new SimpleDateFormat("MMMM").format(date));

(You'll have to put a date with your month in a Date object to use the second option).

Adding a newline character within a cell (CSV)

I was concatenating the variable and adding multiple items in same row. so below code work for me. "\n" new line code is mandatory to add first and last of each line if you will add it on last only it will append last 1-2 character to new lines.

  $itemCode =  '';
foreach($returnData['repairdetail'] as $checkkey=>$repairDetailData){

    if($checkkey >0){
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";
    }else{
        $itemCode   .= "\n".trim(@$repairDetailData['ItemMaster']->Item_Code)."\n";             
    }
    $repairDetaile[]= array(
        $itemCode,
    )
}
// pass all array to here 
foreach ($repairDetaile as $csvData) { 
    fputcsv($csv_file,$csvData,',','"');
}
fclose($csv_file);  

disable horizontal scroll on mobile web

I've found this answer over here on stackoverflow which works perfectly for me:

use this in style

body {
    overflow-x: hidden;
    width: 100%;
}

Use this in head tag

<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />

A slight addition of mine in case your body has padding (to prevent the device from scaling to the body content-box, and thus still adding a horizontal scrollbar):

body {
    overflow-x: hidden;
    width: 100%;
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

Device not detected in Eclipse when connected with USB cable

I had similar problem, drivers was okey, but Eclipse did show me the device in Run > Run Configurations > Target tab. But I checked the option "Always prompt to pick device". And then running the application from Eclipse the prompt window finally showed my device.

What are good examples of genetic algorithms/genetic programming solutions?

I built a simple GA for extracting useful patterns out of the frequency spectrum of music as it was being played. The output was used to drive graphical effects in a winamp plugin.

  • Input: a few FFT frames (imagine a 2D array of floats)
  • Output: single float value (weighted sum of inputs), thresholded to 0.0 or 1.0
  • Genes: input weights
  • Fitness function: combination of duty cycle, pulse width and BPM within sensible range.

I had a few GAs tuned to different parts of the spectrum as well as different BPM limits, so they didn't tend to converge towards the same pattern. The outputs from the top 4 from each population were sent to the rendering engine.

An interesting side effect was that the average fitness across the population was a good indicator for changes in the music, although it generally took 4-5 seconds to figure it out.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

Replace your draw line with

g.drawOval(X - r, Y - r, r, r)

This should make the top-left of your circle the right place to make the center be (X,Y), at least as long as the point (X - r,Y - r) has both components in range.

Fast Bitmap Blur For Android SDK

You can now use ScriptIntrinsicBlur from the RenderScript library to blur quickly. Here is how to access the RenderScript API. The following is a class I made to blur Views and Bitmaps:

public class BlurBuilder {
    private static final float BITMAP_SCALE = 0.4f;
    private static final float BLUR_RADIUS = 7.5f;

    public static Bitmap blur(View v) {
        return blur(v.getContext(), getScreenshot(v));
    }

    public static Bitmap blur(Context ctx, Bitmap image) {
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);

        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

        RenderScript rs = RenderScript.create(ctx);
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);

        return outputBitmap;
    }

    private static Bitmap getScreenshot(View v) {
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        return b;
    }
}

FontAwesome icons not showing. Why?

I got the similar problem, Shows icons in square, tried as per the instructions specified here : https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself

Resolved by using this reference in head section of html page

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css">

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Another way is to use TRANSLATE:

TRANSLATE (col_name, 'x'||CHR(10)||CHR(13), 'x')

The 'x' is any character that you don't want translated to null, because TRANSLATE doesn't work right if the 3rd parameter is null.

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

Remove trailing zeros from decimal in SQL Server

SELECT REVERSE(ROUND(REVERSE(2.5500),1))

prints:

2.55

How to access Session variables and set them in javascript?

You can't access Session directly in JavaScript.

You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

Convert string to date in bash

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'

How to implement a lock in JavaScript

Here's a simple lock mechanism, implemented via closure

_x000D_
_x000D_
const createLock = () => {

    let lockStatus = false

    const release = () => {
        lockStatus = false
    }

    const acuire = () => {
        if (lockStatus == true)
            return false
        lockStatus = true
        return true
    }
    
    return {
        lockStatus: lockStatus, 
        acuire: acuire,
        release: release,
    }
}

lock = createLock() // create a lock
lock.acuire() // acuired a lock

if (lock.acuire()){
  console.log("Was able to acuire");
} else {
  console.log("Was not to acuire"); // This will execute
}

lock.release() // now the lock is released

if(lock.acuire()){
  console.log("Was able to acuire"); // This will execute
} else {
  console.log("Was not to acuire"); 
}

lock.release() // Hey don't forget to release
_x000D_
_x000D_
_x000D_

How to execute a command in a remote computer?

Another solution is to use WMI.NET or Windows Management Instrumentation.

Using the .NET Framework namespace System.Management, you can automate administrative tasks using Windows Management Instrumentation (WMI).

Code Sample

using System.Management;
...
var processToRun = new[] { "notepad.exe" };
var connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", REMOTE_COMPUTER_NAME), connection);
var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
wmiProcess.InvokeMethod("Create", processToRun);

If you have trouble with authentication, then check the DCOM configuration.

  1. On the target machine, run dcomcnfg from the command prompt.
  2. Expand Component Services\Computers\My Computer\DCOM Config
  3. Find Windows Management Instruction, identified with GUID 8BC3F05E-D86B-11D0-A075-00C04FB68820 (you can see this in the details view).
  4. Edit the properties and then add the username you are trying to login with under the permissions tab.
  5. You may need to reboot the service or the entire machine.

NOTE: All paths used for the remote process need to be local to the target machine.

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

Deck of cards JAVA

There is a lot of error in your program.

  1. Calculation of index. I think it should be Math.random()%deck.length

  2. In the display of card. According to me, you should make a class of card which has rank suit and make the array of that class type

If you want I can give you the Complete structure of that but it is better if u make it by yourself

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

It appears that SSRS has an issue(at leastin version 2008) - I'm studying this website that explains it

Where it says if you have two columns(from 2 diff. tables) with the same name, then it'll cause that problem.

From source:

SELECT a.Field1, a.Field2, a.Field3, b.Field1, b.field99 FROM TableA a JOIN TableB b on a.Field1 = b.Field1

SQL handled it just fine, since I had prefixed each with an alias (table) name. But SSRS uses only the column name as the key, not table + column, so it was choking.

The fix was easy, either rename the second column, i.e. b.Field1 AS Field01 or just omit the field all together, which is what I did.

How to fix a header on scroll

Hopefully this one piece of an alternate solution will be as valuable to someone else as it was for me.

Situation:
In an HTML5 page I had a menu that was a nav element inside a header (not THE header but a header in another element).
I wanted the navigation to stick to the top once a user scrolled to it, but previous to this the header was absolute positioned (so I could have it overlay something else slightly).
The solutions above never triggered a change because .offsetTop was not going to change as this was an absolute positioned element. Additionally the .scrollTop property was simply the top of the top most element... that is to say 0 and always would be 0.
Any tests I performed utilizing these two (and same with getBoundingClientRect results) would not tell me if the top of the navigation bar ever scrolled to the top of the viewable page (again, as reported in console, they simply stayed the same numbers while scrolling occurred).

Solution
The solution for me was utilizing

window.visualViewport.pageTop

The value of the pageTop property reflects the viewable section of the screen, therefore allowing me to track where an element is in reference to the boundaries of the viewable area.
This allowed a simple function assigned to the scroll event of the window to detect when the top of the navigation bar intersected with the top of the viewable area and apply the styling to make it stick to the top.

Probably unnecessary to say, anytime I am dealing with scrolling I expect to use this solution to programatically respond to movement of elements being scrolled.
Hope it helps someone else.

std::string to char*

This would be better as a comment on bobobobo's answer, but I don't have the rep for that. It accomplishes the same thing but with better practices.

Although the other answers are useful, if you ever need to convert std::string to char* explicitly without const, const_cast is your friend.

std::string str = "string";
char* chr = const_cast<char*>(str.c_str());

Note that this will not give you a copy of the data; it will give you a pointer to the string. Thus, if you modify an element of chr, you'll modify str.

Why do I get access denied to data folder when using adb?

if you know the application package you can cd directly to that folder..

eg cd data/data/com.yourapp

this will drop you into a directory that is read/writable so you can change files as needed. Since the folder is the same on the emulator, you can use that to get the folder path.

Best way to initialize (empty) array in PHP

What you're doing is 100% correct.

In terms of nice naming it's often done that private/protected properties are preceded with an underscore to make it obvious that they're not public. E.g. private $_arr = array() or public $arr = array()

How to add more than one machine to the trusted hosts list using winrm

winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'

How to replace substrings in windows batch file

SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%

EDIT

Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.

Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:

@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
  SET "line=%%L"
  SETLOCAL ENABLEDELAYEDEXPANSION
  ECHO !line:bath=hello!
  ENDLOCAL
)
ENDLOCAL

You can add a redirection to a file:

  ECHO !line:bath=hello!>>file2.txt

Or you can apply the redirection to the batch file. It must be a different file.

EDIT 2

Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !, ^ et al. (Thanks, jeb!)

What does collation mean?

The collation is how SQL server decides on how to sort and compare text.

See MSDN.

Session 'app' error while installing APK

In my case, my project location contained the special character.

E:\Android_Projects\T&PUIET,KUK\app\build\outputs\apk\app-debug.apk

close android studio > rename folder containing the special character(here T&PUIET,KUK ) > restart android studio.

Hope this Solution helps!

android:layout_height 50% of the screen size

To make sure the height of a view is 50% of the screen then we can create two sub LinearLayouts in a LinearLayout. Each of the child LinearLayout should have "android:layout_weight" of 0.5 to cover half the screen

the parent LinearLAyout should have "android:orientation" set to vertical

.

.

here is code for your reference.... this code contains two buttons of height half the screen

<LinearLayout 
android:orientation="vertical"
android:layout_height="match_parent">

<LinearLayout

    android:layout_weight="0.5"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:padding="10dp"
        android:layout_weight="0.5"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="button1"
        android:id="@+id/button1"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        />

    <Button
        android:padding="10dp"
        android:layout_weight="0.5"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="button2"
        android:id="@+id/button2"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        />

    </LinearLayout>

<LinearLayout

    android:layout_weight="0.5"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">


    </LinearLayout>
   </LinearLayout>

How do you force a CIFS connection to unmount

On RHEL 6 this worked for me also:

umount -f -a -t cifs -l FOLDER_NAME

Increment a database field by 1

Updating an entry:

A simple increment should do the trick.

UPDATE mytable 
  SET logins = logins + 1 
  WHERE id = 12

Insert new row, or Update if already present:

If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE syntax or the INSERT...ON DUPLICATE KEY UPDATE option (As Rob Van Dam demonstrated in his answer).

Inserting a new entry:

Or perhaps you're looking for something like INSERT...MAX(logins)+1? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:

INSERT into mytable (logins) 
  SELECT max(logins) + 1 
  FROM mytable

Redis: Show database size/size for keys

How about redis-cli get KEYNAME | wc -c

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:

import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('[email protected]', 'test1234');
    }
}

def  d_email = "[email protected]",
        d_uname = "email",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "465", //465,587
        m_to = "[email protected]",
        m_subject = "Testing",
        m_text = "Hey, this is the testing email."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

How to break out of a loop from inside a switch?

while(MyCondition) {
switch(msg->state) {
case MSGTYPE: // ... 
    break;
// ... more stuff ...
case DONE:
   MyCondition=false; // just add this code and you will be out of loop.
    break; // **HERE, you want to break out of the loop itself**
}
}

How to remove specific session in asp.net?

There is nothing like session container , so you can set it as null

but rather you can set individual session element as null or ""

like Session["userid"] = null;

How to negate the whole regex?

Use negative lookaround: (?!pattern)

Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.

Links to regular-expressions.info

See also

More examples

These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):

Add new row to excel Table (VBA)

You don't say which version of Excel you are using. This is written for 2007/2010 (a different apprach is required for Excel 2003 )

You also don't say how you are calling addDataToTable and what you are passing into arrData.
I'm guessing you are passing a 0 based array. If this is the case (and the Table starts in Column A) then iCount will count from 0 and .Cells(lLastRow + 1, iCount) will try to reference column 0 which is invalid.

You are also not taking advantage of the ListObject. Your code assumes the ListObject1 is located starting at row 1. If this is not the case your code will place the data in the wrong row.

Here's an alternative that utilised the ListObject

Sub MyAdd(ByVal strTableName As String, ByRef arrData As Variant)
    Dim Tbl As ListObject
    Dim NewRow As ListRow

    ' Based on OP 
    ' Set Tbl = Worksheets(4).ListObjects(strTableName)
    ' Or better, get list on any sheet in workbook
    Set Tbl = Range(strTableName).ListObject
    Set NewRow = Tbl.ListRows.Add(AlwaysInsert:=True)

    ' Handle Arrays and Ranges
    If TypeName(arrData) = "Range" Then
        NewRow.Range = arrData.Value
    Else
        NewRow.Range = arrData
    End If
End Sub

Can be called in a variety of ways:

Sub zx()
    ' Pass a variant array copied from a range
    MyAdd "MyTable", [G1:J1].Value
    ' Pass a range
    MyAdd "MyTable", [G1:J1]
    ' Pass an array
    MyAdd "MyTable", Array(1, 2, 3, 4)
End Sub

How to show matplotlib plots in python

In case anyone else ends up here using Jupyter Notebooks, you just need

%matplotlib inline

Purpose of "%matplotlib inline"

How do I pass a datetime value as a URI parameter in asp.net mvc?

Split out the Year, Month, Day Hours and Mins

routes.MapRoute(
            "MyNewRoute",
            "{controller}/{action}/{Year}/{Month}/{Days}/{Hours}/{Mins}",
            new { controller="YourControllerName", action="YourActionName"}
        );

Use a cascading If Statement to Build up the datetime from the parameters passed into the Action

    ' Build up the date from the passed url or use the current date
    Dim tCurrentDate As DateTime = Nothing
    If Year.HasValue Then
        If Month.HasValue Then
            If Day.HasValue Then
                tCurrentDate = New Date(Year, Month, Day)
            Else
                tCurrentDate = New Date(Year, Month, 1)
            End If
        Else
            tCurrentDate = New Date(Year, 1, 1)
        End If
    Else
        tCurrentDate = StartOfThisWeek(Date.Now)
    End If

(Apologies for the vb.net but you get the idea :P)

Get nodes where child node contains an attribute

I would think your own suggestion is correct, however the xml is not quite valid. If you are running the //book[title[@lang='it']] on <root>[Your"XML"Here]</root> then the free online xPath testers such as one here will find the expected result.

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

To understand this, you must take a step back. In OO, the customer owns the orders (orders are a list in the customer object). There can't be an order without a customer. So the customer seems to be the owner of the orders.

But in the SQL world, one item will actually contain a pointer to the other. Since there is 1 customer for N orders, each order contains a foreign key to the customer it belongs to. This is the "connection" and this means the order "owns" (or literally contains) the connection (information). This is exactly the opposite from the OO/model world.

This may help to understand:

public class Customer {
     // This field doesn't exist in the database
     // It is simulated with a SQL query
     // "OO speak": Customer owns the orders
     private List<Order> orders;
}

public class Order {
     // This field actually exists in the DB
     // In a purely OO model, we could omit it
     // "DB speak": Order contains a foreign key to customer
     private Customer customer;
}

The inverse side is the OO "owner" of the object, in this case the customer. The customer has no columns in the table to store the orders, so you must tell it where in the order table it can save this data (which happens via mappedBy).

Another common example are trees with nodes which can be both parents and children. In this case, the two fields are used in one class:

public class Node {
    // Again, this is managed by Hibernate.
    // There is no matching column in the database.
    @OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
    private List<Node> children;

    // This field exists in the database.
    // For the OO model, it's not really necessary and in fact
    // some XML implementations omit it to save memory.
    // Of course, that limits your options to navigate the tree.
    @ManyToOne
    private Node parent;
}

This explains for the "foreign key" many-to-one design works. There is a second approach which uses another table to maintain the relations. That means, for our first example, you have three tables: The one with customers, the one with orders and a two-column table with pairs of primary keys (customerPK, orderPK).

This approach is more flexible than the one above (it can easily handle one-to-one, many-to-one, one-to-many and even many-to-many). The price is that

  • it's a bit slower (having to maintain another table and joins uses three tables instead of just two),
  • the join syntax is more complex (which can be tedious if you have to manually write many queries, for example when you try to debug something)
  • it's more error prone because you can suddenly get too many or too few results when something goes wrong in the code which manages the connection table.

That's why I rarely recommend this approach.

onclick event function in JavaScript

Yes you should change the name of your function. Javascript has reserved methods and onclick = >>>> click() <<<< is one of them so just rename it, add an 's' to the end of it or something. strong text`

How to read first N lines of a file?

N = 10
with open("file.txt", "a") as file:  # the a opens it in append mode
    for i in range(N):
        line = next(file).strip()
        print(line)

pythonic way to do something N times without an index variable?

Assume that you've defined do_something as a function, and you'd like to perform it N times. Maybe you can try the following:

todos = [do_something] * N  
for doit in todos:  
    doit()

Printing list elements on separated lines in Python

Use the splat operator(*)

By default, * operator prints list separated by space. Use sep operator to specify the delimiter

print(*sys.path, sep = "\n")

ToList().ForEach in Linq

You can use Array.ForEach()

Array.ForEach(employees, employee => {
   Array.ForEach(employee.Departments, department => department.SomeProperty = null);
   Collection.AddRange(employee.Departments);
});

On Selenium WebDriver how to get Text from Span Tag

You need to locate the element and use getText() method to extract the text.

WebElement element = driver.findElement(By.id("customSelect_3"));
System.out.println(element.getText());

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

@GaryK answer is absolutely great, I've spent an hour looking for an explanation orphanRemoval = true vs CascadeType.REMOVE and it helped me understand.

Summing up: orphanRemoval = true works identical as CascadeType.REMOVE ONLY IF we deleting object (entityManager.delete(object)) and we want the childs objects to be removed as well.

In completely different sitiuation, when we fetching some data like List<Child> childs = object.getChilds() and then remove a child (entityManager.remove(childs.get(0)) using orphanRemoval=true will cause that entity corresponding to childs.get(0) will be deleted from database.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

Short Answer:

  • orElse() will always call the given function whether you want it or not, regardless of Optional.isPresent() value
  • orElseGet() will only call the given function when the Optional.isPresent() == false

In real code, you might want to consider the second approach when the required resource is expensive to get.

// Always get heavy resource
getResource(resourceId).orElse(getHeavyResource()); 

// Get heavy resource when required.
getResource(resourceId).orElseGet(() -> getHeavyResource()) 

For more details, consider the following example with this function:

public Optional<String> findMyPhone(int phoneId)

The difference is as below:

                           X : buyNewExpensivePhone() called

+——————————————————————————————————————————————————————————————————+——————————————+
|           Optional.isPresent()                                   | true | false |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElse(buyNewExpensivePhone())          |   X  |   X   |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElseGet(() -> buyNewExpensivePhone()) |      |   X   |
+——————————————————————————————————————————————————————————————————+——————————————+

When optional.isPresent() == false, there is no difference between two ways. However, when optional.isPresent() == true, orElse() always calls the subsequent function whether you want it or not.

Finally, the test case used is as below:

Result:

------------- Scenario 1 - orElse() --------------------
  1.1. Optional.isPresent() == true (Redundant call)
    Going to a very far store to buy a new expensive phone
    Used phone: MyCheapPhone

  1.2. Optional.isPresent() == false
    Going to a very far store to buy a new expensive phone
    Used phone: NewExpensivePhone

------------- Scenario 2 - orElseGet() --------------------
  2.1. Optional.isPresent() == true
    Used phone: MyCheapPhone

  2.2. Optional.isPresent() == false
    Going to a very far store to buy a new expensive phone
    Used phone: NewExpensivePhone

Code:

public class TestOptional {
    public Optional<String> findMyPhone(int phoneId) {
        return phoneId == 10
                ? Optional.of("MyCheapPhone")
                : Optional.empty();
    }

    public String buyNewExpensivePhone() {
        System.out.println("\tGoing to a very far store to buy a new expensive phone");
        return "NewExpensivePhone";
    }


    public static void main(String[] args) {
        TestOptional test = new TestOptional();
        String phone;
        System.out.println("------------- Scenario 1 - orElse() --------------------");
        System.out.println("  1.1. Optional.isPresent() == true (Redundant call)");
        phone = test.findMyPhone(10).orElse(test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("  1.2. Optional.isPresent() == false");
        phone = test.findMyPhone(-1).orElse(test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("------------- Scenario 2 - orElseGet() --------------------");
        System.out.println("  2.1. Optional.isPresent() == true");
        // Can be written as test::buyNewExpensivePhone
        phone = test.findMyPhone(10).orElseGet(() -> test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("  2.2. Optional.isPresent() == false");
        phone = test.findMyPhone(-1).orElseGet(() -> test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");
    }
}

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

Rank function in MySQL

Starting with MySQL 8, you can finally use window functions also in MySQL: https://dev.mysql.com/doc/refman/8.0/en/window-functions.html

Your query can be written exactly the same way:

SELECT RANK() OVER (PARTITION BY Gender ORDER BY Age) AS `Partition by Gender`, 
  FirstName, 
  Age,
  Gender 
FROM Person

How can I make a thumbnail <img> show a full size image when clicked?

That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

check for network issues, to bypass the exception case code

In my case, I was using a custom index, that index had no route and such would trigger the exception case code. The exception case bug still exists and still masks the real issue, however I was able to work around this by testing the connectivity with other tools such as nc -vzw1 myindex.example.org 443 and retrying when the network was up.

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I had the same issue, I fixed it by using org.hibernate.annotations.Table annotation instead of javax.persistence.Table in the Entity class.

import javax.persistence.Entity;
import org.hibernate.annotations.Table;

@Entity
@Table(appliesTo = "my_table")
public class MyTable{
//and rest of the code

Java SSLException: hostname in certificate didn't match

Updating the java version from 1.8.0_40 to 1.8.0_181 resolved the issue.

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

How to store Query Result in variable using mysql

Surround that select with parentheses.

SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;

How can I filter a date of a DateTimeField in Django?

Model.objects.filter(datetime__year=2011, datetime__month=2, datetime__day=30)

Groovy - How to compare the string?

In Groovy, null == null gets a true. At runtime, you won't know what happened. In Java, == is comparing two references.

This is a cause of big confusion in basic programming, Whether it is safe to use equals. At runtime, a null.equals will give an exception. You've got a chance to know what went wrong.

Especially, you get two values from keys not exist in map(s), == makes them equal.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

How correctly produce JSON by RESTful web service?

Use this annotation

@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})

How to define constants in Visual C# like #define in C?

What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)

Also, Python's convention for constants CONSTANT_NAME is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g. public const string ExtractedMagicString = "vs2019";

Source: Defining constants in C#

How to find index of all occurrences of element in array?

Another approach using Array.prototype.map() and Array.prototype.filter():

var indices = array.map((e, i) => e === value ? i : '').filter(String)

Use of "this" keyword in C++

Yes. unless, there is an ambiguity.

How to identify object types in java

You forgot the .class:

if (value.getClass() == Integer.class) {
    System.out.println("This is an Integer");
} 
else if (value.getClass() == String.class) {
    System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
    System.out.println("This is a Float");
}

Note that this kind of code is usually the sign of a poor OO design.

Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:

"foo".getClass() == Object.class

is false, whereas

"foo" instanceof Object

is true.

Whether one or the other must be used depends on your requirements.

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

How to save a git commit message from windows cmd?

You are inside vim. To save changes and quit, type:

<esc> :wq <enter>

That means:

  • Press Escape. This should make sure you are in command mode
  • type in :wq
  • Press Return

An alternative that stdcall in the comments mentions is:

  • Press Escape
  • Press shift+Z shift+Z (capital Z twice).

Ansible playbook shell output

I found using the minimal stdout_callback with ansible-playbook gave similar output to using ad-hoc ansible.

In your ansible.cfg (Note that I'm on OS X so modify the callback_plugins path to suit your install)

stdout_callback     = minimal
callback_plugins    = /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ansible/plugins/callback

So that a ansible-playbook task like yours

---
-
  hosts: example
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5

Gives output like this, like an ad-hoc command would

example | SUCCESS | rc=0 >>
%CPU USER     COMMAND
 0.2 root     sshd: root@pts/3
 0.1 root     /usr/sbin/CROND -n
 0.0 root     [xfs-reclaim/vda]
 0.0 root     [xfs_mru_cache]

I'm using ansible-playbook 2.2.1.0

How can I determine browser window size on server side C#

There is a solution to solve page_onload problem (can't get size until page load complete) : Create a userControl :

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ClientSizeDetector.ascx.vb"    Inherits="Project_UserControls_ClientSizeDetector" %>
<%If (IsFirstTime) Then%>
<script type="text/javascript">
var pageURL = window.location.href.search(/\?/) > 0 ? "&" : "?";
window.location.href = window.location.href + pageURL + "clientHeight=" + window.innerHeight + "&clientWidth=" + window.innerWidth;
</script>
<%End If%>

Code behind :

 Private _isFirstTime As Boolean = False
 Private _clientWidth As Integer = 0
 Private _clientHeight As Integer = 0

 Public Property ClientWidth() As Integer
    Get
        Return _clientWidth
    End Get
    Set(value As Integer)
        _clientWidth = value
    End Set
End Property

Public Property ClientHeight() As Integer
    Get
        Return _clientHeight
    End Get
    Set(value As Integer)
        _clientHeight = value
    End Set
End Property

public Property IsFirstTime() As Boolean 
    Get
        Return _isFirstTime
    End Get
    Set(value As Boolean)
        _isFirstTime = value
    End Set
End Property



Protected Overrides Sub OnInit(e As EventArgs)

    If (String.IsNullOrEmpty(Request.QueryString("clientHeight")) Or String.IsNullOrEmpty(Request.QueryString("clientWidth"))) Then
        Me._isFirstTime = True
    Else
        Integer.TryParse(Request.QueryString("clientHeight").ToString(), ClientHeight)
        Integer.TryParse(Request.QueryString("clientWidth").ToString(), ClientWidth)
        Me._isFirstTime = False
    End If
End Sub

So after, you can call your control properties

Create Pandas DataFrame from a string

In one line, but first import IO

import pandas as pd
import io   

TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""

df = pd.read_csv(  io.StringIO(TESTDATA)  , sep=";")
print ( df )

Get current URL/URI without some of $_GET variables

You are definitely searching for this

Yii::app()->request->pathInfo

how to empty recyclebin through command prompt?

All of the answers are way too complicated. OP requested a way to do this from CMD.

Here you go (from cmd file):

powershell.exe /c "$(New-Object -ComObject Shell.Application).NameSpace(0xA).Items() | %%{Remove-Item $_.Path -Recurse -Confirm:$false"

And yes, it will update in explorer.

Now() function with time trim

You could also use Format$(Now(), "Short Date") or whatever date format you want. Be aware, this function will return the Date as a string, so using Date() is a better approach.

How to fix/convert space indentation in Sublime Text?

I found, in my mind, a simpler solution than Magne:

On mac:

"cmd+f" => "  "(two spaces) => "alt+enter" => "arrow right" => "  "(two more spaces) => set tab width to 4(this can be done before or after.

On windows or other platforms change cmd+f and alt+enter with whatever your find and select all hotkeys are.

Note: this method is prone to "errors" if you have more than one space within your code. It is thus less safe than Magne's method, but it is faster (for me at least).

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

What is a PDB file?

Program Debug Database file (pdb) is a file format by Microsoft for storing debugging information.

When you build a project using Visual Studio or command prompt the compiler creates these symbol files.

Check Microsoft Docs

How to redirect Valgrind's output to a file?

In addition to the other answers (particularly by Lekakis), some string replacements can also be used in the option --log-file= as elaborated in the Valgrind's user manual.

Four replacements were available at the time of writing:

  • %p: Prints the current process ID
    • valgrind --log-file="myFile-%p.dat" <application-name>
  • %n: Prints file sequence number unique for the current process
    • valgrind --log-file="myFile-%p-%n.dat" <application-name>
  • %q{ENV}: Prints contents of the environment variable ENV
    • valgrind --log-file="myFile-%q{HOME}.dat" <application-name>
  • %%: Prints %
    • valgrind --log-file="myFile-%%.dat" <application-name>

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

How to get text and a variable in a messagebox

As has been suggested, using the string.format method is nice and simple and very readable.

In vb.net the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)

becomes:

MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx

maybe call

variable.ToString()

update:

Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")

jQuery click anywhere in the page except on 1 div

I know that this question has been answered, And all the answers are nice. But I wanted to add my two cents to this question for people who have similar (but not exactly the same) problem.

In a more general way, we can do something like this:

$('body').click(function(evt){    
    if(!$(evt.target).is('#menu_content')) {
        //event handling code
    }
});

This way we can handle not only events fired by anything except element with id menu_content but also events that are fired by anything except any element that we can select using CSS selectors.

For instance in the following code snippet I am getting events fired by any element except all <li> elements which are descendants of div element with id myNavbar.

$('body').click(function(evt){    
    if(!$(evt.target).is('div#myNavbar li')) {
        //event handling code
    }
});

Should I use int or Int32

Some compilers have different sizes for int on different platforms (not C# specific)

Some coding standards (MISRA C) requires that all types used are size specified (i.e. Int32 and not int).

It is also good to specify prefixes for different type variables (e.g. b for 8 bit byte, w for 16 bit word, and l for 32 bit long word => Int32 lMyVariable)

You should care because it makes your code more portable and more maintainable.

Portable may not be applicable to C# if you are always going to use C# and the C# specification will never change in this regard.

Maintainable ihmo will always be applicable, because the person maintaining your code may not be aware of this particular C# specification, and miss a bug were the int occasionaly becomes more than 2147483647.

In a simple for-loop that counts for example the months of the year, you won't care, but when you use the variable in a context where it could possibly owerflow, you should care.

You should also care if you are going to do bit-wise operations on it.

PHP Fatal error: Uncaught exception 'Exception'

Just adding a bit of extra information here in case someone has the same issue as me.

I use namespaces in my code and I had a class with a function that throws an Exception.

However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.

Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.

Find index of last occurrence of a sub-string using T-SQL

Some of the other answers return an actual string whereas I had more need to know the actual index int. And the answers that do that seem to over-complicate things. Using some of the other answers as inspiration, I did the following...

First, I created a function:

CREATE FUNCTION [dbo].[LastIndexOf] (@stringToFind varchar(max), @stringToSearch varchar(max))
RETURNS INT
AS
BEGIN
    RETURN (LEN(@stringToSearch) - CHARINDEX(@stringToFind,REVERSE(@stringToSearch))) + 1
END
GO

Then, in your query you can simply do this:

declare @stringToSearch varchar(max) = 'SomeText: SomeMoreText: SomeLastText'

select dbo.LastIndexOf(':', @stringToSearch)

The above should return 23 (the last index of ':')

Hope this made it a little easier for someone!

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

select unique rows based on single distinct column

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

Inserting the same value multiple times when formatting a string

Fstrings

If you are using Python 3.6+ you can make use of the new so called f-strings which stands for formatted strings and it can be used by adding the character f at the beginning of a string to identify this as an f-string.

price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!

The main benefits of using f-strings is that they are more readable, can be faster, and offer better performance:

Source Pandas for Everyone: Python Data Analysis, By Daniel Y. Chen

Benchmarks

No doubt that the new f-strings are more readable, as you don't have to remap the strings, but is it faster though as stated in the aformentioned quote?

price = 123
name = "Jerry"

def new():
    x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"


def old():
    x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)

import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776  #new
> 5.861819514350163   #old

Running 10 Million test's it seems that the new f-strings are actually faster in mapping.

How can I find a specific element in a List<T>?

You can create a search variable to hold your searching criteria. Here is an example using database.

 var query = from o in this.mJDBDataset.Products 
             where o.ProductStatus == textBox1.Text || o.Karrot == textBox1.Text 
             || o.ProductDetails == textBox1.Text || o.DepositDate == textBox1.Text 
             || o.SellDate == textBox1.Text
             select o;

 dataGridView1.DataSource = query.ToList();

 //Search and Calculate
 search = textBox1.Text;
 cnn.Open();
 string query1 = string.Format("select * from Products where ProductStatus='"
               + search +"'");
 SqlDataAdapter da = new SqlDataAdapter(query1, cnn);
 DataSet ds = new DataSet();
 da.Fill(ds, "Products");
 SqlDataReader reader;
 reader = new SqlCommand(query1, cnn).ExecuteReader();

 List<double> DuePayment = new List<double>();

 if (reader.HasRows)
 {

  while (reader.Read())
  {

   foreach (DataRow row in ds.Tables["Products"].Rows)
   {

     DuePaymentstring.Add(row["DuePayment"].ToString());
     DuePayment = DuePaymentstring.Select(x => double.Parse(x)).ToList();

   }
  }

  tdp = 0;
  tdp = DuePayment.Sum();                        
  DuePaymentstring.Remove(Convert.ToString(DuePaymentstring.Count));
  DuePayment.Clear();
 }
 cnn.Close();
 label3.Text = Convert.ToString(tdp + " Due Payment Count: " + 
 DuePayment.Count + " Due Payment string Count: " + DuePaymentstring.Count);
 tdp = 0;
 //DuePaymentstring.RemoveRange(0,DuePaymentstring.Count);
 //DuePayment.RemoveRange(0, DuePayment.Count);
 //Search and Calculate

Here "var query" is generating the search criteria you are giving through the search variable. Then "DuePaymentstring.Select" is selecting the data matching your given criteria. Feel free to ask if you have problem understanding.

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=utf-8");
    return headers;
}

You need to add Content-Type to the header.

How to disable text selection highlighting

A JavaScript solution for Internet Explorer is:

onselectstart="return false;"

Similarity String Comparison in Java

You could use Levenshtein distance to calculate the difference between two strings. http://en.wikipedia.org/wiki/Levenshtein_distance

How do I undo 'git add' before commit?

git rm --cached . -r

will "un-add" everything you've added from your current directory recursively

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

How to change the text on the action bar

try do this...

public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
    this.setTitle(String.format(your_format_string, your_personal_text_to_display));
    setContentView(R.layout.your_layout);
       ...
       ...
}

it works for me

Focus Next Element In Tab Index

function focusNextElement(){
  var focusable = [].slice.call(document.querySelectorAll("a, button, input, select, textarea, [tabindex], [contenteditable]")).filter(function($e){
    if($e.disabled || ($e.getAttribute("tabindex") && parseInt($e.getAttribute("tabindex"))<0)) return false;
    return true;
  }).sort(function($a, $b){
    return (parseFloat($a.getAttribute("tabindex") || 99999) || 99999) - (parseFloat($b.getAttribute("tabindex") || 99999) || 99999);
  });
  var focusIndex = focusable.indexOf(document.activeElement);
  if(focusable[focusIndex+1]) focusable[focusIndex+1].focus();
};

How to convert a factor to integer\numeric without loss of information?

type.convert(f) on a factor whose levels are completely numeric is another base option.

Performance-wise it's about equivalent to as.numeric(as.character(f)) but not nearly as quick as as.numeric(levels(f))[f].

identical(type.convert(f), as.numeric(levels(f))[f])

[1] TRUE

That said, if the reason the vector was created as a factor in the first instance has not been addressed (i.e. it likely contained some characters that could not be coerced to numeric) then this approach won't work and it will return a factor.

levels(f)[1] <- "some character level"
identical(type.convert(f), as.numeric(levels(f))[f])

[1] FALSE

How do I replace a character in a string in Java?

If you're using Spring you can simply call HtmlUtils.htmlEscape(String input) which will handle the '&' to '&' translation.

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

Changing .gitconfig location on Windows

I'm no Git master, but from searching around the solution that worked easiest for me was to just go to C:\Program Files (x86)\Git\etc and open profile in a text editor.

There's an if statement on line 37 # Set up USER's home directory. I took out the if statement and put in the local directory that I wanted the gitconfig to be, then I just copied my existing gitconfig file (was on a network drive) to that location.

response.sendRedirect() from Servlet to JSP does not seem to work

I'm posting this answer because the one with the most votes led me astray. To redirect from a servlet, you simply do this:

response.sendRedirect("simpleList.do")

In this particular question, I think @M-D is correctly explaining why the asker is having his problem, but since this is the first result on google when you search for "Redirect from Servlet" I think it's important to have an answer that helps most people, not just the original asker.

How do I get the result of a command in a variable in windows?

You should use the for command, here is an example:

@echo off
rem Commands go here
exit /b
:output
for /f "tokens=* useback" %%a in (`%~1`) do set "output=%%a"

and you can use call :output "Command goes here" then the output will be in the %output% variable.

Note: If you have a command output that is multiline, this tool will set the output to the last line of your multiline command.

Check if property has attribute

You can use a common (generic) method to read attribute over a given MemberInfo

public static bool TryGetAttribute<T>(MemberInfo memberInfo, out T customAttribute) where T: Attribute {
                var attributes = memberInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
                if (attributes == null) {
                    customAttribute = null;
                    return false;
                }
                customAttribute = (T)attributes;
                return true;
            }

Convert an ArrayList to an object array

Convert an ArrayList to an object array

ArrayList has a constructor that takes a Collection, so the common idiom is:

List<T> list = new ArrayList<T>(Arrays.asList(array));

Which constructs a copy of the list created by the array.

now, Arrays.asList(array) will wrap the array, so changes to the list will affect the array, and visa versa. Although you can't add or remove

elements from such a list.

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Another thing is - if your keys are very complicated sometimes you need to replace the places of the fields and it helps :

if this dosent work:

foreign key (ISBN, Title) references BookTitle (ISBN, Title)

Then this might work (not for this specific example but in general) :

foreign key (Title,ISBN) references BookTitle (Title,ISBN)

GDB: break if variable equal value

There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:

http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html

To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.

watch command is used to set a watchpoit for writing, while rwatch for reading, and awatch for reading/writing.

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

Transmitting newline character "\n"

Try to replace the \n with %0A just like you have spaces replaced with %20.

ERROR! MySQL manager or server PID file could not be found! QNAP

Nothing of this worked for me. I tried everything and nothing worked.

I just did :

brew unlink mysql && brew install mariadb

My concern was if I would lost all the data, but luckily everything was there.

Hope it works for somebody else

What is the difference between a URI, a URL and a URN?

They're the same thing. A URI is a generalization of a URL. Originally, URIs were planned to be divided into URLs (addresses) and URNs (names) but then there was little difference between a URL and URI and http URIs were used as namespaces even though they didn't actually locate any resources.

Angular ui-grid dynamically calculate height of the grid

.ui-grid, .ui-grid-viewport,.ui-grid-contents-wrapper, .ui-grid-canvas { height: auto !important; }

Convert Float to Int in Swift

var floatValue = 10.23
var intValue = Int(floatValue)

This is enough to convert from float to Int

Extract substring from a string

When finding multiple occurrences of a substring matching a pattern

    String input_string = "foo/adsfasdf/adf/bar/erqwer/";
    String regex = "(foo/|bar/)"; // Matches 'foo/' and 'bar/'

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input_string);

    while(matcher.find()) {
      String str_matched = input_string.substring(matcher.start(), matcher.end());
        // Do something with a match found
    }

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

So it turns out that the .NET files were copied to C:\Program Files\Microsoft.NET\Primary Interop Assemblies\. However, they were never registered in the GAC.

I ended up manually dragging the files in C:\Program Files\Microsoft.NET\Primary Interop Assemblies to C:\windows\assembly and the application worked on that problem machine. You could also do this programmatically with Gacutil.

So it seems that something happened to .NET during the install, but this seems to correct the problem. I hope that helps someone else out!

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

Since the google policies update, you need to enable billing to access Map API.

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

Did you check the Configuration manager settings? In the project settings dialog top right corner.

Sometimes it happens that between all the release entries a debug entry comes in. If so, the auto dependency created by the dependency graph of the solution gets all confused.

What is the best Java email address validation method?

Using the official java email package is the easiest:

public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}

How to configure Glassfish Server in Eclipse manually

For Eclipse Luna

Go to Help>Eclipse MarketPlace> Search for GlassFish Tools and install it.

Restart Eclipse.

Now go to servers>new>server and you will find Glassfish server.

Calling functions in a DLL from C++

There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.

CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbols then it is probably better to NOT USE the definition file approach.

Here is an simple example on how this is done.

Step 1: Define the function in the export.h file.

int WINAPI IsolatedFunction(const char *title, const char *test);

Step 2: Define the function in the export.cpp file.

#include <windows.h>

int WINAPI IsolatedFunction(const char *title, const char *test)
{
    MessageBox(0, title, test, MB_OK);
    return 1;
}

Step 3: Define the function as an export in the export.def defintion file.

EXPORTS    IsolatedFunction          @1

Step 4: Create a DLL project and add the export.cpp and export.def files to this project. Building this project will create an export.dll and an export.lib file.

The following two steps link to the DLL at link time. If you don't want to define the entry points at link time, ignore the next two steps and use the LoadLibrary and GetProcAddress to load the function entry point at runtime.

Step 5: Create a Test application project to use the dll by adding the export.lib file to the project. Copy the export.dll file to ths same location as the Test console executable.

Step 6: Call the IsolatedFunction function from within the Test application as shown below.

#include "stdafx.h"

// get the function prototype of the imported function
#include "../export/export.h"

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    // call the imported function found in the dll
    int result = IsolatedFunction("hello", "world");

    return 0;
}

How to test Spring Data repositories?

With Spring Boot + Spring Data it has become quite easy:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    MyRepository subject;

    @Test
    public void myTest() throws Exception {
        subject.save(new MyEntity());
    }
}

The solution by @heez brings up the full context, this only bring up what is needed for JPA+Transaction to work. Note that the solution above will bring up a in memory test database given that one can be found on the classpath.

How to insert a character in a string at a certain position?

int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);

What's the difference between passing by reference vs. passing by value?

First and foremost, the "pass by value vs. pass by reference" distinction as defined in the CS theory is now obsolete because the technique originally defined as "pass by reference" has since fallen out of favor and is seldom used now.1

Newer languages2 tend to use a different (but similar) pair of techniques to achieve the same effects (see below) which is the primary source of confusion.

A secondary source of confusion is the fact that in "pass by reference", "reference" has a narrower meaning than the general term "reference" (because the phrase predates it).


Now, the authentic definition is:

  • When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable.

  • When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.

Things to note in this definition are:

  • "Variable" here means the caller's (local or global) variable itself -- i.e. if I pass a local variable by reference and assign to it, I'll change the caller's variable itself, not e.g. whatever it is pointing to if it's a pointer.

    • This is now considered bad practice (as an implicit dependency). As such, virtually all newer languages are exclusively, or almost exclusively pass-by-value. Pass-by-reference is now chiefly used in the form of "output/inout arguments" in languages where a function cannot return more than one value.
  • The meaning of "reference" in "pass by reference". The difference with the general "reference" term is that this "reference" is temporary and implicit. What the callee basically gets is a "variable" that is somehow "the same" as the original one. How specifically this effect is achieved is irrelevant (e.g. the language may also expose some implementation details -- addresses, pointers, dereferencing -- this is all irrelevant; if the net effect is this, it's pass-by-reference).


Now, in modern languages, variables tend to be of "reference types" (another concept invented later than "pass by reference" and inspired by it), i.e. the actual object data is stored separately somewhere (usually, on the heap), and only "references" to it are ever held in variables and passed as parameters.3

Passing such a reference falls under pass-by-value because a variable's value is technically the reference itself, not the referred object. However, the net effect on the program can be the same as either pass-by-value or pass-by-reference:

  • If a reference is just taken from a caller's variable and passed as an argument, this has the same effect as pass-by-reference: if the referred object is mutated in the callee, the caller will see the change.
    • However, if a variable holding this reference is reassigned, it will stop pointing to that object, so any further operations on this variable will instead affect whatever it is pointing to now.
  • To have the same effect as pass-by-value, a copy of the object is made at some point. Options include:
    • The caller can just make a private copy before the call and give the callee a reference to that instead.
    • In some languages, some object types are "immutable": any operation on them that seems to alter the value actually creates a completely new object without affecting the original one. So, passing an object of such a type as an argument always has the effect of pass-by-value: a copy for the callee will be made automatically if and when it needs a change, and the caller's object will never be affected.
      • In functional languages, all objects are immutable.

As you may see, this pair of techniques is almost the same as those in the definition, only with a level of indirection: just replace "variable" with "referenced object".

There's no agreed-upon name for them, which leads to contorted explanations like "call by value where the value is a reference". In 1975, Barbara Liskov suggested the term "call-by-object-sharing" (or sometimes just "call-by-sharing") though it never quite caught on. Moreover, neither of these phrases draws a parallel with the original pair. No wonder the old terms ended up being reused in the absence of anything better, leading to confusion.4


NOTE: For a long time, this answer used to say:

Say I want to share a web page with you. If I tell you the URL, I'm passing by reference. You can use that URL to see the same web page I can see. If that page is changed, we both see the changes. If you delete the URL, all you're doing is destroying your reference to that page - you're not deleting the actual page itself.

If I print out the page and give you the printout, I'm passing by value. Your page is a disconnected copy of the original. You won't see any subsequent changes, and any changes that you make (e.g. scribbling on your printout) will not show up on the original page. If you destroy the printout, you have actually destroyed your copy of the object - but the original web page remains intact.

This is mostly correct except the narrower meaning of "reference" -- it being both temporary and implicit (it doesn't have to, but being explicit and/or persistent are additional features, not a part of the pass-by-reference semantic, as explained above). A closer analogy would be giving you a copy of a document vs inviting you to work on the original.


1Unless you are programming in Fortran or Visual Basic, it's not the default behavior, and in most languages in modern use, true call-by-reference is not even possible.

2A fair amount of older ones support it, too

3In several modern languages, all types are reference types. This approach was pioneered by the language CLU in 1975 and has since been adopted by many other languages, including Python and Ruby. And many more languages use a hybrid approach, where some types are "value types" and others are "reference types" -- among them are C#, Java, and JavaScript.

4There's nothing bad with recycling a fitting old term per se, but one has to somehow make it clear which meaning is used each time. Not doing that is exactly what keeps causing confusion.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Try this:

int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);  
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];

How to get the selected item of a combo box to a string variable in c#

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);

dropdownlist set selected value in MVC3 Razor

You should use view models and forget about ViewBag Think of it as if it didn't exist. You will see how easier things will become. So define a view model:

public class MyViewModel
{
    public int SelectedCategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; } 
}

and then populate this view model from the controller:

public ActionResult NewsEdit(int ID, dms_New dsn)
{
    var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
    var categories = (from b in dc.dms_NewsCategories select b).ToList();

    var model = new MyViewModel
    {
        SelectedCategoryId = dsn.NewsCategoriesID,
        Categories = categories.Select(x => new SelectListItem
        {
            Value = x.NewsCategoriesID.ToString(),
            Text = x.NewsCategoriesName
        })
    };
    return View(model);
}

and finally in your view use the strongly typed DropDownListFor helper:

@model MyViewModel

@Html.DropDownListFor(
    x => x.SelectedCategoryId,
    Model.Categories
)

Is it possible to pass parameters programmatically in a Microsoft Access update query?

You can also use TempVars - note '!' syntax is essential You can also use TempVars - note '!' syntax is essential

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

I have occurred the same error look following example-

async.waterfall([function(waterCB) {
    waterCB(null);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.

Cheak your function parameters Below are a correct example.

async.waterfall([function(waterCB) {
    waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

Thanks

Could not resolve Spring property placeholder

Ensure 'idm.url' is set in property file and the property file is loaded

Truncate (not round) decimal places in SQL Server

ROUND(number, decimals, operation)

number => Required. The number to be rounded
decimals => Required. The number of decimal places to round number to
operation => Optional. If 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0

SELECT ROUND(235.415, 2, 1)

will give you 235.410

SELECT ROUND(235.415, 0, 1)

will give you 235.000

But now trimming0 you can use cast

SELECT CAST(ROUND(235.415, 0, 1) AS INT)

will give you 235

node.js string.replace doesn't work?

Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).

So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Best way to log POST data in Apache?

Though It's late to answer. This module can do: https://github.com/danghvu/mod_dumpost

Python Pandas Error tokenizing data

The following worked for me (I posted this answer, because I specifically had this problem in a Google Colaboratory Notebook):

df = pd.read_csv("/path/foo.csv", delimiter=';', skiprows=0, low_memory=False)

Ruby on Rails: how to render a string as HTML?

Use raw:

<%=raw @str >

But as @jmort253 correctly says, consider where the HTML really belongs.

How to disable Home and other system buttons in Android?

Post ICS i.e. Android 4+, the overriding of the HomeButton has been removed for security reasons, to enable the user exit in case the application turns out to be a malware.

Plus, it is not a really good practice to not let the user navigate away from the application. But, since you are making a lock screen application, what you can do is declare the activity as a Launcher , so that when the HomeButton is pressed it will simply restart your application and remain there itself (the users would notice nothing but a slight flicker in the screen).

You can go through the following link:

http://dharmendra4android.blogspot.in/2012/05/override-home-button-in-android.html

Running Node.js in apache?

If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:

<?php
    shell_exec("node nodeScript.js"); // without arguments
    shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>

The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:

<?php
    $evilUserData = "'; [malicious commands here];";
    shell_exec("node nodeScript.js '{$evilUserData}'");
?>

What does <> mean?

Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

Then solution will be the following.

HTML

<div class="parent">
    <div class="child"></div>
</div>

CSS

.parent{
        width: 960px;
        margin: auto;
        height: 100vh
    }
    .child{
        position: absolute;
        width: 100vw
    }

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

How to convert HH:mm:ss.SSS to milliseconds?

You can use SimpleDateFormat to do it. You just have to know 2 things.

  1. All dates are internally represented in UTC
  2. .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.
package se.wederbrand.milliseconds;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {        
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        String inputString = "00:01:30.500";

        Date date = sdf.parse("1970-01-01 " + inputString);
        System.out.println("in milliseconds: " + date.getTime());        
    }
}

C# Creating and using Functions

Note: in C# the term "function" is often replaced by the term "method". For the sake of this question there is no difference, so I'll just use the term "function".

Thats not true. you may read about (func type+ Lambda expressions),( anonymous function"using delegates type"),(action type +Lambda expressions ),(Predicate type+Lambda expressions). etc...etc... this will work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

           int a;
           int b;
           int c;

           Console.WriteLine("Enter value of 'a':");
           a = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("Enter value of 'b':");
           b = Convert.ToInt32(Console.ReadLine());

           Func<int, int, int> funcAdd = (x, y) => x + y;
           c=funcAdd.Invoke(a, b);
           Console.WriteLine(Convert.ToString(c));

        }

     }
}

How to make a launcher

Just develop a normal app and then add a couple of lines to the app's manifest file.

First you need to add the following attribute to your activity:

            android:launchMode="singleTask"

Then add two categories to the intent filter :

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.HOME" />

The result could look something like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dummy.app"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="11"
            android:targetSdkVersion="19" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.dummy.app.MainActivity"
                android:launchMode="singleTask"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.HOME" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

It's that simple!

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Converting to unix timestamps makes doing date math easier in php:

$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );

// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
  $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}

When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

The difference is the amount of memory allocated to each integer, and how large a number they each can store.

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

When to use dynamic vs. static libraries

A static library must be linked into the final executable; it becomes part of the executable and follows it wherever it goes. A dynamic library is loaded every time the executable is executed and remains separate from the executable as a DLL file.

You would use a DLL when you want to be able to change the functionality provided by the library without having to re-link the executable (just replace the DLL file, without having to replace the executable file).

You would use a static library whenever you don't have a reason to use a dynamic library.

Cannot find java. Please use the --jdkhome switch

I do recommend you to change the configuration of JDK used by NetBeans in netbeans.conf config file:

netbeans_jdkhome="C:\Program Files\Java\..."

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

How to validate an e-mail address in swift?

Swift 5 - Scalable Validation Layer

Using this layer you will get amazing validations over any text field easily.

Just follow the following process.

1. Add these enums:

import Foundation

enum ValidatorType
{
    case email
    case name
    // add more cases ...
}

enum ValidationError: Error, LocalizedError
{
    case invalidUserName
    case invalidEmail
    // add more cases ...

    var localizedDescription: String
    {
        switch self
        {
        case .invalidEmail:
            return "Please kindly write a valid email"    
        case .invalidUserName:
            return "Please kindly write a valid user name"
        }
    }
}

2. Add this functionality to String:

extension String
{
    // MARK:- Properties

    var isValidEmail: Bool
    {
        let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
        return emailPredicate.evaluate(with: self)
    }

    // MARK:- Methods

    func validatedText(_ validationType: ValidatorType) throws
    {
        switch validationType
        {
            case .name:
                try validateUsername()
            case .email:
                try validateEmail()
        }
    }

    // MARK:- Private Methods

    private func validateUsername() throws
    {
        if isEmpty
        {
            throw ValidationError.invalidUserName
        }
    }

    private func validateEmail() throws
    {
        if !isValidEmail 
        {
            throw ValidationError.invalidEmail
        }

        // add more validations if you want like empty email
    }
}

3. Add the following functionality to UITextField:

import UIKit

extension UITextField
{
    func validatedText(_ validationType: ValidatorType) throws
    {
        do
        {
            try text?.validatedText(validationType)
        }
        catch let validationError
        {
            shake()
            throw validationError
        }
    }

    // MARK:- Private Methods

    private func shake()
    {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.1
        animation.repeatCount = 5
        animation.fromValue = NSValue(cgPoint: CGPoint(x: center.x + 6, y: center.y))
        animation.toValue = NSValue(cgPoint: CGPoint(x: center.x - 6, y: center.y))
        layer.add(animation, forKey: "position")
    }
}

Usage

import UIKit

class LoginVC: UIViewController
{
    // MARK: Outlets

    @IBOutlet weak var textFieldEmail: UITextField!

    // MARK: View Controller Life Cycle

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    // MARK: Methods

    private func checkEmail() -> Bool
    {
        do
        {
            try textFieldEmail.validatedText(.email)
        }
        catch let error
        {
            let validationError = error as! ValidationError
            // show alert to user with: validationError.localizedDescription
            return false
        }

        return true
    }

    // MARK: Actions

    @IBAction func loginTapped(_ sender: UIButton)
    {
        if checkEmail()
        {
            let email = textFieldEmail.text!
            // move safely ...
        }
    }
}

Chrome Extension - Get DOM content

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

Regarding your question if content scripts or background pages are the way to go:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.


Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

background.js:

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}

Formatting a number with exactly two decimals in JavaScript

Here's a TypeScript implementation of https://stackoverflow.com/a/21323330/916734. It also dries things up with functions, and allows for a optional digit offset.

export function round(rawValue: number | string, precision = 0, fractionDigitOffset = 0): number | string {
  const value = Number(rawValue);
  if (isNaN(value)) return rawValue;

  precision = Number(precision);
  if (precision % 1 !== 0) return NaN;

  let [ stringValue, exponent ] = scientificNotationToParts(value);

  let shiftExponent = exponentForPrecision(exponent, precision, Shift.Right);
  const enlargedValue = toScientificNotation(stringValue, shiftExponent);
  const roundedValue = Math.round(enlargedValue);

  [ stringValue, exponent ] = scientificNotationToParts(roundedValue);
  const precisionWithOffset = precision + fractionDigitOffset;
  shiftExponent = exponentForPrecision(exponent, precisionWithOffset, Shift.Left);

  return toScientificNotation(stringValue, shiftExponent);
}

enum Shift {
  Left = -1,
  Right = 1,
}

function scientificNotationToParts(value: number): Array<string> {
  const [ stringValue, exponent ] = value.toString().split('e');
  return [ stringValue, exponent ];
}

function exponentForPrecision(exponent: string, precision: number, shift: Shift): number {
  precision = shift * precision;
  return exponent ? (Number(exponent) + precision) : precision;
}

function toScientificNotation(value: string, exponent: number): number {
  return Number(`${value}e${exponent}`);
}

How to create/read/write JSON files in Qt5

Example: Read json from file

/* test.json */
{
   "appDesc": {
      "description": "SomeDescription",
      "message": "SomeMessage"
   },
   "appName": {
      "description": "Home",
      "message": "Welcome",
      "imp":["awesome","best","good"]
   }
}


void readJson()
   {
      QString val;
      QFile file;
      file.setFileName("test.json");
      file.open(QIODevice::ReadOnly | QIODevice::Text);
      val = file.readAll();
      file.close();
      qWarning() << val;
      QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
      QJsonObject sett2 = d.object();
      QJsonValue value = sett2.value(QString("appName"));
      qWarning() << value;
      QJsonObject item = value.toObject();
      qWarning() << tr("QJsonObject of description: ") << item;

      /* in case of string value get value and convert into string*/
      qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
      QJsonValue subobj = item["description"];
      qWarning() << subobj.toString();

      /* in case of array get array and convert into string*/
      qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
      QJsonArray test = item["imp"].toArray();
      qWarning() << test[1].toString();
   }

OUTPUT

QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) 
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) 
"QJsonObject[appName] of description: " QJsonValue(string, "Home") 
"Home" 
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) 
"best" 

Example: Read json from string

Assign json to string as below and use the readJson() function shown before:

val =   
'  {
       "appDesc": {
          "description": "SomeDescription",
          "message": "SomeMessage"
       },
       "appName": {
          "description": "Home",
          "message": "Welcome",
          "imp":["awesome","best","good"]
       }
    }';

OUTPUT

QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) ) 
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) 
"QJsonObject[appName] of description: " QJsonValue(string, "Home") 
"Home" 
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) ) 
"best" 

How to set default vim colorscheme

Your .vimrc file goes in your $HOME directory. In *nix, cd ~; vim .vimrc. The commands in the .vimrc are the same as you type in ex-mode in vim, only without the leading colon, so colo evening would suffice. Comments in the .vimrc are indicated with a leading double-quote.

To see an example vimrc, open $VIMRUNTIME/vimrc_example.vim from within vim

:e $VIMRUNTIME/vimrc_example.vim

Change HTML email body font type and size in VBA

Set texts with different sizes and styles, and size and style for texts from cells ( with Range)

Sub EmailManuellAbsenden()

Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String

Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
.GetInspector.Display
 ghOldBody = .htmlBody

 ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
 "<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
 Range("B5") & "<br>" & _
 Range("B6") & "<br>" & _
 "<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
 Range("B5")
 .htmlBody = ghNewBody & ghOldBody

 End With

End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

Use mysql_fetch_array() with foreach() instead of while()

You can code like this:

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
foreach($rows as $row){ 
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
}

As you can see, it's still need a loop while to get data from mysql_fetch_array

Double free or corruption after queue::push

Um, shouldn't the destructor be calling delete, rather than delete[]?

Setting max-height for table cell contents

Just put the labels in a div inside the TD and put the height and overflow.. like below.

<table>
<tr>
  <td><div style="height:40px; overflow:hidden">Sample</div></td>
  <td><div style="height:40px; overflow:hidden">Text</div></td>
  <td><div style="height:40px; overflow:hidden">Here</div></td>
</tr>
</table>

Android ClassNotFoundException: Didn't find class on path

In my case it was proguard minification process that removed some important classes from my production apk.

The solution was to edit the proguard-rules.pro file and add the following:

-keep class com.someimportant3rdpartypackage.** { *; }

Change GitHub Account username

Yes, it's possible. But first read, "What happens when I change my username?"

To change your username, click your profile picture in the top right corner, then click Settings. On the left side, click Account. Then click Change username.

How to change an Eclipse default project into a Java project

Open the .project file and add java nature and builders.

<projectDescription>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>

And in .classpath, reference the Java libs:

<classpath>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

How to get current time with jQuery

Using JavaScript native Date functions you can get hours, minutes and seconds as you want. If you wish to format date and time in particular way you may want to implement a method extending JavaScript Date prototype.

Here is one already implemented: https://github.com/jacwright/date.format

Application Installation Failed in Android Studio

Again in this issue also I found Instant Run buggy. When I disable the Instant run and run the app again App starts successfully installing in the Device without showing any error Window. I hope google will sort out these Issues with Instant run soon.

Steps to disable Instant Run from Android Studio:

File > Settings > Build,Execution,Deployment > Instant Run > Un-check (Enable Instant Run to hot swap code)