Programs & Examples On #Image editing

prevent iphone default keyboard when focusing an <input>

@rene-pot is correct. You will however have a not-allowed sign on the desktop version of the website. Way around this, apply the readonly="true" to a div that will show up on the mobile view only and not on desktop. See what we did here http://www.naivashahotels.com/naivasha-hotels/lake-naivasha-country-club/

RecyclerView inside ScrollView is not working

The best solution is to keep multiple Views in a Single View / View Group and then keep that one view in the SrcollView. ie.

Format -

<ScrollView> 
  <Another View>
       <RecyclerView>
       <TextView>
       <And Other Views>
  </Another View>
</ScrollView>

Eg.

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView           
              android:text="any text"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>


        <TextView           
              android:text="any text"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"/>
 </ScrollView>

Another Eg. of ScrollView with multiple Views

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:orientation="vertical"
            android:layout_weight="1">

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#FFFFFF"
                />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingHorizontal="10dp"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/CategoryItem"
                    android:textSize="20sp"
                    android:textColor="#000000"
                    />

                <TextView
                    android:textColor="#000000"
                    android:text="?1000"
                    android:textSize="18sp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:textColor="#000000"
                    android:text="so\nugh\nos\nghs\nrgh\n
                    sghs\noug\nhro\nghreo\nhgor\ngheroh\ngr\neoh\n
                    og\nhrf\ndhog\n
                    so\nugh\nos\nghs\nrgh\nsghs\noug\nhro\n
                    ghreo\nhgor\ngheroh\ngr\neoh\nog\nhrf\ndhog"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>

             </LinearLayout>

        </LinearLayout>

</ScrollView>

MySQL table is marked as crashed and last (automatic?) repair failed

I needed to add USE_FRM to the repair statement to make it work.

REPAIR TABLE <table_name> USE_FRM;

How to use java.Set

It's difficult to answer this question with the information given. Nothing looks particularly wrong with how you are using HashSet.

Well, I'll hazard a guess that it's not a compilation issue and, when you say "getting errors," you mean "not getting the behavior [you] want."

I'll also go out on a limb and suggest that maybe your Block's equals an hashCode methods are not properly overridden.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

#include<stdio.h>
#include<conio.h>
void main()
{
int len=0,revnum,i,dup=0,j=0,k=0;

 long int gvalue;

 char  ones[]  [10]={"one","Two","Three","Four","Five","Six","Seven","Eight","Nine","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen",""};

 char twos[][10]={"Ten","Twenty","Thirty","Fourty","fifty","Sixty","Seventy","eighty","Ninety",""};

clrscr();


 printf("\n Enter value"); 

 scanf("%ld",&gvalue);
 if(gvalue==10)

   printf("Ten");

 else if(gvalue==100)

   printf("Hundred");

 else if(gvalue==1000)

   printf("Thousand");

 dup=gvalue;

 for(i=0;dup>0;i++)
  {
   revnum=revnum*10+dup%10;

   len++;

   dup=dup/10;

  }

 while(j<len)

 {

 if(gvalue<10)

  {

   printf("%s ",ones[gvalue-1]);

   }

 else if(gvalue>10&&gvalue<=19)

  {

   printf("%s ",ones[gvalue-2]);

   break;

  }

 else if(gvalue>19&&gvalue<100)

  {

   k=gvalue/10;

   gvalue=gvalue%10;

    printf("%s ",twos[k-1]);

   }

  else if(gvalue>100&&gvalue<1000)

   {

    k=gvalue/100;

    gvalue=gvalue%100;

    printf("%s Hundred ",ones[k-1]);

     }

   else if(gvalue>=1000&&gvlaue<9999)

   {

    k=gvalue/1000;

    gvalue=gvalue%1000;

    printf("%s Thousand ",ones[k-1]);

    }

   else if(gvalue>=11000&&gvalue<=19000)

    {

    k=gvalue/1000;

    gvalue=gvalue%1000;

    printf("%s Thousand ",twos[k-2]);

    }

   else if(gvalue>=12000&&gvalue<100000)

   {

    k=gvalue/10000;

    gvalue=gvalue%10000;

    printf("%s ",ones[gvalue-1]);

   }

else

{

printf("");

}

 j++;

 getch();

}

React-Native Button style not work

I know this is necro-posting, but I found a real easy way to just add the margin-top and margin-bottom to the button itself without having to build anything else.

When you create the styles, whether inline or by creating an object to pass, you can do this:

var buttonStyle = {
   marginTop: "1px",
   marginBottom: "1px"
}

It seems that adding the quotes around the value makes it work. I don't know if this is because it's a later version of React versus what was posted two years ago, but I know that it works now.

jQuery: click function exclude children.

Or you can do also:

$('.example').on('click', function(e) { 
   if( e.target != this ) 
       return false;

   // ... //
});

How to pass parameters to a Script tag?

JQuery has a way to pass parameters from HTML to javascript:

Put this in the myhtml.html file:

<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>

In the same directory make a subscript.js file and put this in there:

//Use jquery to look up the tag with the id of 'myscript' above.  Get 
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");

//print filename out to screen.
document.write(filename);

Analyze Result:

Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.

jsfiddle proof that the above works:

http://jsfiddle.net/xqr77dLt/

How to select <td> of the <table> with javascript?

This d = t.getElementsByTagName("tr") and this r = d.getElementsByTagName("td") are both arrays. The getElementsByTagName returns an collection of elements even if there's just one found on your match.

So you have to use like this:

var t = document.getElementById("table"), // This have to be the ID of your table, not the tag
    d = t.getElementsByTagName("tr")[0],
    r = d.getElementsByTagName("td")[0];

Place the index of the array as you want to access the objects.

Note that getElementById as the name says just get the element with matched id, so your table have to be like <table id='table'> and getElementsByTagName gets by the tag.

EDIT:

Well, continuing this post, I think you can do this:

var t = document.getElementById("table");
var trs = t.getElementsByTagName("tr");
var tds = null;

for (var i=0; i<trs.length; i++)
{
    tds = trs[i].getElementsByTagName("td");
    for (var n=0; n<tds.length;n++)
    {
        tds[n].onclick=function() { alert(this.innerHTML); }
    }
}

Try it!

Can not find module “@angular-devkit/build-angular”

I tried all the possible commands listed above and none of them worked for me, Check if Package.json contain "@angular-devkit/build-angular" if not just install it using(in my case version 0.803.19 worked)

npm i @angular-devkit/[email protected]

Or checkout at npm website repositories for version selection

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

What is a callback in java

A callback is some code that you pass to a given method, so that it can be called at a later time.

In Java one obvious example is java.util.Comparator. You do not usually use a Comparator directly; rather, you pass it to some code that calls the Comparator at a later time:

Example:

class CodedString implements Comparable<CodedString> {
    private int code;
    private String text;

    ...

    @Override
    public boolean equals() {
        // member-wise equality
    }

    @Override
    public int hashCode() {
        // member-wise equality 
    }

    @Override
    public boolean compareTo(CodedString cs) {
        // Compare using "code" first, then
        // "text" if both codes are equal.
    }
}

...

public void sortCodedStringsByText(List<CodedString> codedStrings) {
    Comparator<CodedString> comparatorByText = new Comparator<CodedString>() {
        @Override
        public int compare(CodedString cs1, CodedString cs2) {
            // Compare cs1 and cs2 using just the "text" field
        }
    }

    // Here we pass the comparatorByText callback to Collections.sort(...)
    // Collections.sort(...) will then call this callback whenever it
    // needs to compare two items from the list being sorted.
    // As a result, we will get the list sorted by just the "text" field.
    // If we do not pass a callback, Collections.sort will use the default
    // comparison for the class (first by "code", then by "text").
    Collections.sort(codedStrings, comparatorByText);
}

Split text with '\r\n'

Following code gives intended results.

string text="some interesting text\nsome text that should be in the same line\r\nsome 
text should be in another line"
var results = text.Split(new[] {"\n","\r\n"}, StringSplitOptions.None);

How to fast get Hardware-ID in C#?

For more details refer to this link

The following code will give you CPU ID:

namespace required System.Management

var mbs = new ManagementObjectSearcher("Select ProcessorId From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
    id = mo["ProcessorId"].ToString();
    break;
}

For Hard disk ID and motherboard id details refer this-link

To speed up this procedure, make sure you don't use SELECT *, but only select what you really need. Use SELECT * only during development when you try to find out what you need to use, because then the query will take much longer to complete.

How to get the list of all printers in computer

Look at the static System.Drawing.Printing.PrinterSettings.InstalledPrinters property.

It is a list of the names of all installed printers on the system.

What command means "do nothing" in a conditional in Bash?

The no-op command in shell is : (colon).

if [ "$a" -ge 10 ]
then
    :
elif [ "$a" -le 5 ]
then
    echo "1"
else
    echo "2"
fi

From the bash manual:

: (a colon)
Do nothing beyond expanding arguments and performing redirections. The return status is zero.

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Something important to add: When using INSERT IGNORE and you do have key violations, MySQL does NOT raise a warning!

If you try for instance to insert 100 records at a time, with one faulty one, you would get in interactive mode:

Query OK, 99 rows affected (0.04 sec)

Records: 100 Duplicates: 1 Warnings: 0

As you see: No Warnings! This behavior is even wrongly described in the official Mysql Documentation.

If your script needs to be informed, if some records have not been added (due to key violations) you have to call mysql_info() and parse it for the "Duplicates" value.

Programmatically register a broadcast receiver

According to Listening For and Broadcasting Global Messages, and Setting Alarms in Common Tasks and How to Do Them in Android:

If the receiving class is not registered using in its manifest, you can dynamically instantiate and register a receiver by calling Context.registerReceiver().

Take a look at registerReceiver (BroadcastReceiver receiver, IntentFilter filter) for more info.

Viewing local storage contents on IE

In IE11, you can see local storage in console on dev tools:

  1. Show dev tools (press F12)
  2. Click "Console" or press Ctrl+2
  3. Type localStorage and press Enter

Also, if you need to clear the localStorage, type localStorage.clear() on console.

Unable to send email using Gmail SMTP server through PHPMailer, getting error: SMTP AUTH is required for message submission on port 587. How to fix?

I think it is connection issue you can get code here http://skillrow.com/sending-mail-using-smtp-and-php/

include(“smtpfile.php“);
include(“saslfile.php“); // for SASL authentication $from=”[email protected]“; //from mail id

$smtp=new smtp_class;

$smtp->host_name=”www.abc.com“; // name of host
$smtp->host_port=25;//port of host

$smtp->timeout=10;
$smtp->data_timeout=0;
$smtp->debug=1;
$smtp->html_debug=1;
$smtp->pop3_auth_host=””;
$smtp->ssl=0;
$smtp->start_tls=0;
$smtp->localhost=”localhost“;
$smtp->direct_delivery=0;

$smtp->user=”smtp username”;
$smtp->realm=””;
$smtp->password=”smtp password“;

$smtp->workstation=””;
$smtp->authentication_mechanism=””;

$mail=$smtp->SendMessage($from,array($to),array(“From:$from”,”To: $to”,”Subject: $subject”,”Date: ”.strftime(“%a, %d %b %Y %H:%M:%S %Z”)),”$message”);

if($mail){
   echo “Mail sent“;
}else{
   echo $smtp->error;
}

How to select top n rows from a datatable/dataview in ASP.NET

If you want the number of rows to be flexible, you can add row_number in the SQL. For SQL server:

SELECT ROW_NUMBER() OVER (ORDER BY myOrder) ROW_NUMBER, * FROM myTable

Then filter the datatable on row_number:

Dataview dv= new Dataview(dt, "ROW_NUMBER<=100", "", CurrentRows)

Converting JSON data to Java object

Oddly, the only decent JSON processor mentioned so far has been GSON.

Here are more good choices:

  • Jackson (Github) -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
  • Flex-JSON -- highly configurable serialization

EDIT (Aug/2013):

One more to consider:

  • Genson -- functionality similar to Jackson, aimed to be easier to configure by developer

ValueError: Wrong number of items passed - Meaning and suggestions?

for i in range(100):
try:
  #Your code here
  break
except:
  continue

This one worked for me.

How to write a multidimensional array to a text file?

Pickle is best for these cases. Suppose you have a ndarray named x_train. You can dump it into a file and revert it back using the following command:

import pickle

###Load into file
with open("myfile.pkl","wb") as f:
    pickle.dump(x_train,f)

###Extract from file
with open("myfile.pkl","rb") as f:
    x_temp = pickle.load(f)

Sorting an array in C?

I'd like to make some changes: In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
   int int_a = * ( (int*) a );
   int int_b = * ( (int*) b );

   // an easy expression for comparing
   return (int_a > int_b) - (int_a < int_b);
}

qsort( a, 6, sizeof(int), compare )

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

How to add "Maven Managed Dependencies" library in build path eclipse?

Likely quite simple but best way is to edit manually the file .classpath at the root of your project folder with something like

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
        </attributes>
    </classpathentry>

when you want to have jar in your WEB-IN/lib folder (case for a web app)

Which keycode for escape key with jQuery

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

http://jaywcjlove.github.io/hotkeys/

hotkeys('enter,esc', function(event,handler){
    switch(handler.key){
        case "enter":$('.save').click();break;
        case "esc":$('.cancel').click();break;
    }
});

hotkeys understands the following modifiers: ?,shiftoption?altctrlcontrolcommand, and ?.

The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.

Rails where condition using NOT NIL

It's not a bug in ARel, it's a bug in your logic.

What you want here is:

Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))

How to style CSS role

The shortest way to write a selector that accesses that specific div is to simply use

[role=main] {
  /* CSS goes here */
}

The previous answers are not wrong, but they rely on you using either a div or using the specific id. With this selector, you'll be able to have all kinds of crazy markup and it would still work and you avoid problems with specificity.

_x000D_
_x000D_
[role=main] {_x000D_
  background: rgba(48, 96, 144, 0.2);_x000D_
}_x000D_
div,_x000D_
span {_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="content" role="main">_x000D_
  <span role="main">Hello</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to open an existing project in Eclipse?

From the main menu bar, select command link File > Import.... The Import wizard opens.
Select General > Existing Project into Workspace and click Next.
Choose either Select root directory or Select archive file and click the associated Browse to locate the directory or file containing the projects.
Under Projects select the project or projects which you would like to import.
Click Finish to start the import.

Copy every nth line from one sheet to another

Create a macro and use the following code to grab the data and put it in a new sheet (Sheet2):

Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1

For i = 1 To 700 Step 7
    strCellNum = "A" & i
    strValue = Worksheets("Sheet1").Range(strCellNum).Value
    Debug.Print strValue
    Worksheets("Sheet2").Range("A" & x).Value = strValue
    x = x + 1
Next

Let me know if this helps! JFV

Remove Array Value By index in jquery

delete arr[1]

Try this out, it should work if you have an array like var arr =["","",""]

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

For anyone who is still having this issue, this worked for me:

    cordova platform update android@latest

then build and it will automatically download the newest gradle version and should work

What is the difference between <section> and <div>?

<section> marks up a section, <div> marks up a generic block with no associated semantics.

How to turn off caching on Firefox?

Firefox 48 Developer Tools

Allows you to turn off cache only when toolbox is open, which is perfect for web development:

  • F12
  • gearbox on right upper corner
  • scroll down top Advanced settings
  • check "Disable Cache (when toolbox is open)"

enter image description here

https://stackoverflow.com/a/27397425/895245 has similar content, but positioning changed a bit since.

Heroku: How to push different local Git branches to Heroku/master

Also note that if your using the git flow system and your feature branch might be called

feature/mobile_additions

and with a git remote called stagingtwo, then the command to push to heroku would be

git push stagingtwo feature/mobile_additions:master

Design DFA accepting binary strings divisible by a number 'n'

Below, I have written an answer for n equals to 5, but you can apply same approach to draw DFAs for any value of n and 'any positional number system' e.g binary, ternary...

First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).

Design DFA accepting Binary numbers divisible by number 'n':

Step-1: When you divide a number ? by n then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0 that means ? is divisible by n otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r, where 0 <= r <= (n - 1), and total number of states in DFA is n.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).

In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:

  1. State q0 reached if reminder is 0. State q0 is the final state(accepting state). It is also an initial state.
  2. State q1 reaches if reminder is 1, a non-final state.
  3. State q2 if reminder is 2, a non-final state.
  4. State q3 if reminder is 3, a non-final state.
  5. State q4 if reminder is 4, a non-final state.

Using above information, we can start drawing transition diagram TD of five states as follows:

fig-1
Figure-1

So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0' at state q0, this is because decimal equivalent of any string consist of only '0' is 0 and 0 is a divisible by n.

Step-2: TD above is incomplete; and can only process strings of '0's. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:

+-------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦
+------+------+-------------+---------¦
¦One   ¦1     ¦1            ¦q1       ¦
+------+------+-------------+---------¦
¦Two   ¦10    ¦2            ¦q2       ¦
+------+------+-------------+---------¦
¦Three ¦11    ¦3            ¦q3       ¦
+------+------+-------------+---------¦
¦Four  ¦100   ¦4            ¦q4       ¦
+-------------------------------------+
  1. To process binary string '1' there should be a transition rule d:(q0, 1)?q1
  2. Two:- binary representation is '10', end-state should be q2, and to process '10', we just need to add one more transition rule d:(q1, 0)?q2
    Path: ?(q0)-1?(q1)-0?(q2)
  3. Three:- in binary it is '11', end-state is q3, and we need to add a transition rule d:(q1, 1)?q3
    Path: ?(q0)-1?(q1)-1?(q3)
  4. Four:- in binary '100', end-state is q4. TD already processes prefix string '10' and we just need to add a new transition rule d:(q2, 0)?q4
    Path: ?(q0)-1?(q1)-0?(q2)-0?(q4)

fig-2 Figure-2

Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'.
Because '101' = 5 is divisible by 5, and to accept '101' I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:

fig-3 Figure-3

Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.

Step-4: Six = 110.

We can process '11' in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.

fig-4 Figure-4

Step-5: Seven = 111

+--------------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path       ¦ Add       ¦
+------+------+-------------+---------+------------+-----------¦
¦Seven ¦111   ¦7 % 5 = 2    ¦q2       ¦ q0-11?q3   ¦ q3-1?q2    ¦
+--------------------------------------------------------------+

fig-5 Figure-5

Step-6: Eight = 1000

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Eight ¦1000  ¦8 % 5 = 3    ¦q3       ¦q0-100?q4 ¦ q4-0?q3  ¦
+----------------------------------------------------------+

fig-6 Figure-6

Step-7: Nine = 1001

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Nine  ¦1001  ¦9 % 5 = 4    ¦q4       ¦q0-100?q4 ¦ q4-1?q4  ¦
+----------------------------------------------------------+

fig-7 Figure-7

In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.

Design DFA accepting Ternary numbers divisible by number n:

Step-1 Exactly same as for binary, use figure-1.

Step-2 Add Zero, One, Two

+------------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦   Add        ¦
+-------+-------+-------------+---------+--------------¦
¦Zero   ¦0      ¦0            ¦q0       ¦ d:(q0,0)?q0  ¦
+-------+-------+-------------+---------+--------------¦
¦One    ¦1      ¦1            ¦q1       ¦ d:(q0,1)?q1  ¦
+-------+-------+-------------+---------+--------------¦
¦Two    ¦2      ¦2            ¦q2       ¦ d:(q0,2)?q3  ¦
+------------------------------------------------------+

fig-8
Figure-8

Step-3 Add Three, Four, Five

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Three  ¦10     ¦3            ¦q3       ¦ d:(q1,0)?q3 ¦
+-------+-------+-------------+---------+-------------¦
¦Four   ¦11     ¦4            ¦q4       ¦ d:(q1,1)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Five   ¦12     ¦0            ¦q0       ¦ d:(q1,2)?q0 ¦
+-----------------------------------------------------+

fig-9
Figure-9

Step-4 Add Six, Seven, Eight

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Six    ¦20     ¦1            ¦q1       ¦ d:(q2,0)?q1 ¦
+-------+-------+-------------+---------+-------------¦
¦Seven  ¦21     ¦2            ¦q2       ¦ d:(q2,1)?q2 ¦
+-------+-------+-------------+---------+-------------¦
¦Eight  ¦22     ¦3            ¦q3       ¦ d:(q2,2)?q3 ¦
+-----------------------------------------------------+

fig-10
Figure-10

Step-5 Add Nine, Ten, Eleven

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Nine   ¦100    ¦4            ¦q4       ¦ d:(q3,0)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Ten    ¦101    ¦0            ¦q0       ¦ d:(q3,1)?q0 ¦
+-------+-------+-------------+---------+-------------¦
¦Eleven ¦102    ¦1            ¦q1       ¦ d:(q3,2)?q1 ¦
+-----------------------------------------------------+

fig-11
Figure-11

Step-6 Add Twelve, Thirteen, Fourteen

+------------------------------------------------------+
¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+--------+-------+-------------+---------+-------------¦
¦Twelve  ¦110    ¦2            ¦q2       ¦ d:(q4,0)?q2 ¦
+--------+-------+-------------+---------+-------------¦
¦Thirteen¦111    ¦3            ¦q3       ¦ d:(q4,1)?q3 ¦
+--------+-------+-------------+---------+-------------¦
¦Fourteen¦112    ¦4            ¦q4       ¦ d:(q4,2)?q4 ¦
+------------------------------------------------------+

fig-12
Figure-12

Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r)!

To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).

If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).

Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n and base b read paper: Divisibility and State Complexity.

below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.

Design DFA for base 'b' number strings divisible by number 'n':

So we can apply above trick to draw DFA to recognize number strings in any base 'b' those are divisible a given number 'n'. In that DFA total number of states will be n (for n remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.

Using above trick, below I have written a Python Script to Draw DFA for input base and number. In script, function divided_by_N populates DFA's transition rules in base * number steps. In each step-num, I convert num into number string num_s using function baseN(). To avoid processing each number string, I have used a temporary data-structure lookup_table. In each step, end-state for number string num_s is evaluated and stored in lookup_table to use in next step.

For transition graph of DFA, I have written a function draw_transition_graph using Pygraphviz library (very easy to use). To use this script you need to install graphviz. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict function.

#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice

def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    """ converts a number `n` into base `b` string """
    return ((n == 0) and syms[0]) or (
        baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])

def divided_by_N(number, base):
    """
    constructs DFA that accepts given `base` number strings
    those are divisible by a given `number`
    """
    ACCEPTING_STATE = START_STATE = '0'
    SYMBOL_0 = '0'
    dfa = {
        str(from_state): {
            str(symbol): 'to_state' for symbol in range(base)
        }
        for from_state in range(number)
    }
    dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
    # `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
    lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
    for num in range(number * base):
        end_state = str(num % number)
        num_s = baseN(num, base)
        before_end_state = lookup_table(num_s[:-1], START_STATE)
        dfa[before_end_state][num_s[-1]] = end_state
        lookup_table(num_s, end_state)
    return dfa

def symcolrhexcodes(symbols):
    """
    returns dict of color codes mapped with alphabets symbol in symbols
    """
    return {
        symbol: '#'+''.join([
            rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
        ])
        for symbol in symbols
    }

def draw_transition_graph(dfa, filename="filename"):
    ACCEPTING_STATE = START_STATE = '0'
    colors = symcolrhexcodes(dfa[START_STATE].keys())
    # draw transition graph
    tg = pgv.AGraph(strict=False, directed=True, decorate=True)
    for from_state in dfa:
        for symbol, to_state in dfa[from_state].iteritems():
            tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
                        label=symbol, color=colors[symbol],
                        fontcolor=colors[symbol])

    # add intial edge from an invisible node!
    tg.add_node('null', shape='plaintext', label='start')
    tg.add_edge('null', "Q%s"%START_STATE,)

    # make end acception state as 'doublecircle'
    tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
    tg.draw(filename, prog='circo')
    tg.close()

def print_transition_table(dfa):
    print("DFA accepting number string in base '%(base)s' "
            "those are divisible by '%(number)s':" % {
                'base': len(dfa['0']),
                'number': len(dfa),})
    pprint(dfa)

if __name__ == "__main__":
    number = input ("Enter NUMBER: ")
    base = input ("Enter BASE of number system: ")
    dfa = divided_by_N(number, base)

    print_transition_table(dfa)
    draw_transition_graph(dfa)

Execute it:

~/study/divide-5/script$ python script.py 
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
 '1': {'0': '4', '1': '0', '2': '1', '3': '2'},
 '2': {'0': '3', '1': '4', '2': '0', '3': '1'},
 '3': {'0': '2', '1': '3', '2': '4', '3': '0'},
 '4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename

Output:

base_4_divided_5_best
DFA accepting number strings in base 4 those are divisible by 5

Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename to .png or .jpeg.

References those I use to write this script:
➊ Function baseN from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

That usually means a null is being posted to the query instead of your desired value, you might try to run the SQL Profiler to see exactly what is getting passed to SQL Server from linq.

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Storing Python dictionaries

My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.

To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list or an object as root. So I considered that my JSON file always has a list of objects and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w):

def saveJson(url,sc): # This function writes the two values to the file
    newdata = {'url':url,'sc':sc}
    json_path = "db/file.json"

    old_list= []
    with open(json_path) as myfile:  # Read the contents first
        old_list = json.load(myfile)
    old_list.append(newdata)

    with open(json_path,"w") as myfile:  # Overwrite the whole content
        json.dump(old_list, myfile, sort_keys=True, indent=4)

    return "success"

The new JSON file will look something like this:

[
    {
        "sc": "a11",
        "url": "www.google.com"
    },
    {
        "sc": "a12",
        "url": "www.google.com"
    },
    {
        "sc": "a13",
        "url": "www.google.com"
    }
]

NOTE: It is essential to have a file named file.json with [] as initial data for this approach to work

PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.

Get week day name from a given month, day and year individually in SQL Server

If you have SQL Server 2012:

If your date parts are integers then you can use DATEFROMPARTS function.

SELECT DATENAME( dw, DATEFROMPARTS( @Year, @Month, @Day ) )

If your date parts are strings, then you can use the CONCAT function.

SELECT DATENAME( dw, CONVERT( date, CONCAT( @Day, '/' , @Month, '/', @Year ), 103 ) )

What is event bubbling and capturing?

If there are two elements element 1 and element 2. Element 2 is inside element 1 and we attach an event handler with both the elements lets say onClick. Now when we click on element 2 then eventHandler for both the elements will be executed. Now here the question is in which order the event will execute. If the event attached with element 1 executes first it is called event capturing and if the event attached with element 2 executes first this is called event bubbling. As per W3C the event will start in the capturing phase until it reaches the target comes back to the element and then it starts bubbling

The capturing and bubbling states are known by the useCapture parameter of addEventListener method

eventTarget.addEventListener(type,listener,[,useCapture]);

By Default useCapture is false. It means it is in the bubbling phase.

_x000D_
_x000D_
var div1 = document.querySelector("#div1");_x000D_
var div2 = document.querySelector("#div2");_x000D_
_x000D_
div1.addEventListener("click", function (event) {_x000D_
  alert("you clicked on div 1");_x000D_
}, true);_x000D_
_x000D_
div2.addEventListener("click", function (event) {_x000D_
  alert("you clicked on div 2");_x000D_
}, false);
_x000D_
#div1{_x000D_
  background-color:red;_x000D_
  padding: 24px;_x000D_
}_x000D_
_x000D_
#div2{_x000D_
  background-color:green;_x000D_
}
_x000D_
<div id="div1">_x000D_
  div 1_x000D_
  <div id="div2">_x000D_
    div 2_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please try with changing true and false.

Receiving login prompt using integrated windows authentication

Windows authentication in IIS7.0 or IIS7.5 does not work with kerberos (provider=Negotiate) when the application pool identity is ApplicationPoolIdentity One has to use Network Service or another build-in account. Another possibility is to use NTLM to get Windows Authenticatio to work (in Windows Authentication, Providers, put NTLM on top or remove negotiate)

chris van de vijver

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

To fix this issue you need to remove your Google account, then add it again. To do this follow these instructions:

http://support.google.com/android/bin/answer.py?hl=en&answer=1663649

(Or just find the account under Settings > Personal > Accounts and Sync > Click the Google Account > Click Menu button > Click Remove Account > Confirm deletion.)

REST API error return good practices

Agreed. The basic philosophy of REST is to use the web infrastructure. The HTTP Status codes are the messaging framework that allows parties to communicate with each other without increasing the HTTP payload. They are already established universal codes conveying the status of response, and therefore, to be truly RESTful, the applications must use this framework to communicate the response status.

Sending an error response in a HTTP 200 envelope is misleading, and forces the client (api consumer) to parse the message, most likely in a non-standard, or proprietary way. This is also not efficient - you will force your clients to parse the HTTP payload every single time to understand the "real" response status. This increases processing, adds latency, and creates an environment for the client to make mistakes.

How to check sbt version?

$ sbt sbtVersion

This prints the sbt version used in your current project, or if it is a multi-module project for each module.

$ sbt 'inspect sbtVersion'
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.1
[info] Description:
[info]  Provides the version of sbt.  This setting should be not be modified.
[info] Provided by:
[info]  */*:sbtVersion
[info] Defined at:
[info]  (sbt.Defaults) Defaults.scala:68
[info] Delegates:
[info]  *:sbtVersion
[info]  {.}/*:sbtVersion
[info]  */*:sbtVersion
[info] Related:
[info]  */*:sbtVersion

You may also want to use sbt about that (copying Mark Harrah's comment):

The about command was added recently to try to succinctly print the most relevant information, including the sbt version.

What is the difference between synchronous and asynchronous programming (in node.js)

This would become a bit more clear if you add a line to both examples:

var result = database.query("SELECT * FROM hugetable");
console.log(result.length);
console.log("Hello World");

The second one:

database.query("SELECT * FROM hugetable", function(rows) {
   var result = rows;
   console.log(result.length);
});
console.log("Hello World");

Try running these, and you’ll notice that the first (synchronous) example, the result.length will be printed out BEFORE the 'Hello World' line. In the second (the asynchronous) example, the result.length will (most likely) be printed AFTER the "Hello World" line.

That's because in the second example, the database.query is run asynchronously in the background, and the script continues straightaway with the "Hello World". The console.log(result.length) is only executed when the database query has completed.

Preloading images with jQuery

I usually use this snippet of code on my projects for the loading of the images in a page. You can see the result here https://jsfiddle.net/ftor34ey/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<img src="https://live.staticflickr.com/65535/50020763321_d61d49e505_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50021019427_692a8167e9_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020228418_d730efe386_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020230828_7ef175d07c_k_d.jpg" width="100" />

<div style="background-image: url(https://live.staticflickr.com/65535/50020765826_e8da0aacca_k_d.jpg);"></div>
<style>
    .bg {
        background-image: url("https://live.staticflickr.com/65535/50020765651_af0962c22e_k_d.jpg");
    }
</style>
<div class="bg"></div>

<div id="loadingProgress"></div>

The script save in an array all the src and background-image of the page and load all of them.

You can see/read/show the progress of the loading by the var loadCount.

let backgroundImageArray = [];

function backgroundLoading(i) {

    let loadCount = 0;

    let img = new Image();
    $(img).on('load', function () {

        if (i < backgroundImageArray.length) {

            loadCount = parseInt(((100 / backgroundImageArray.length) * i));
            backgroundLoading(i + 1);

        } else {

            loadCount = 100;
            // do something when the page finished to load all the images
            console.log('loading completed!!!');
            $('#loadingProgress').append('<div>loading completed!!!</div>');

        }

        console.log(loadCount + '%');
        $('#loadingProgress').append('<div>' + loadCount + '%</div>');

    }).attr('src', backgroundImageArray[i - 1]);

}

$(document).ready(function () {

    $('*').each(function () {

        var backgroundImage = $(this).css('background-image');
        var putInArray = false;

        var check = backgroundImage.substr(0, 3);

        if (check == 'url') {

            backgroundImage = backgroundImage.split('url(').join('').split(')').join('');
            backgroundImage = backgroundImage.replace('"', '');
            backgroundImage = backgroundImage.replace('"', '');

            if (backgroundImage.substr(0, 4) == 'http') {
                backgroundImage = backgroundImage;
            }
            putInArray = true;

        } else if ($(this).get(0).tagName == 'IMG') {

            backgroundImage = $(this).attr('src');
            putInArray = true;

        }

        if (putInArray) {
            backgroundImageArray[backgroundImageArray.length] = backgroundImage;
        }

    });

    backgroundLoading(1);

});

Get all directories within directory nodejs

Recursive solution

I came here in search of a way to get all of the subdirectories, and all of their subdirectories, etc. Building on the accepted answer, I wrote this:

const fs = require('fs');
const path = require('path');

function flatten(lists) {
  return lists.reduce((a, b) => a.concat(b), []);
}

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath)
    .map(file => path.join(srcpath, file))
    .filter(path => fs.statSync(path).isDirectory());
}

function getDirectoriesRecursive(srcpath) {
  return [srcpath, ...flatten(getDirectories(srcpath).map(getDirectoriesRecursive))];
}

How can I print the contents of an array horizontally?

Using Console.Write only works if the thread is the only thread writing to the Console, otherwise your output may be interspersed with other output that may or may not insert newlines, as well as other undesired characters. To ensure your array is printed intact, use Console.WriteLine to write one string. Most any array of objects can be printed horizontally (depending on the type's ToString() method) using the non-generic Join available before .NET 4.0:

        int[] numbers = new int[100];
        for(int i= 0; i < 100; i++)
        {
            numbers[i] = i;
        }

        //For clarity
        IEnumerable strings = numbers.Select<int, string>(j=>j.ToString());
        string[] stringArray = strings.ToArray<string>();
        string output = string.Join(", ", stringArray);
        Console.WriteLine(output);

        //OR 

        //For brevity
        Console.WriteLine(string.Join(", ", numbers.Select<int, string>(j => j.ToString()).ToArray<string>()));

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

How to recover Git objects damaged by hard disk failure?

I have resolved this problem to add some change like git add -A and git commit again.

How to merge a Series and DataFrame

You can easily set a pandas.DataFrame column to a constant. This constant can be an int such as in your example. If the column you specify isn't in the df, then pandas will create a new column with the name you specify. So after your dataframe is constructed, (from your question):

df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6])

You can just run:

df['s1'], df['s2'] = 5, 6

You could write a loop or comprehension to make it do this for all the elements in a list of tuples, or keys and values in a dictionary depending on how you have your real data stored.

How do I import a pre-existing Java project into Eclipse and get up and running?

In the menu go to : - File - Import - as the filter select 'Existing Projects into Workspace' - click next - browse to the project directory at 'select root directory' - click on 'finish'

android get real path by Uri.getPath()

This is what I do:

Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

and:

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

NOTE: managedQuery() method is deprecated, so I am not using it.

Last edit: Improvement. We should close cursor!!

How to replace comma (,) with a dot (.) using java

in the java src you can add a new tool like this:

public static String remplaceVirguleParpoint(String chaine) {
       return chaine.replaceAll(",", "\\.");
}

How to send a header using a HTTP request through a curl call?

man curl:

   -H/--header <header>
          (HTTP)  Extra header to use when getting a web page. You may specify
          any number of extra headers. Note that if you should  add  a  custom
          header that has the same name as one of the internal ones curl would
          use, your externally set header will be used instead of the internal
          one.  This  allows  you  to make even trickier stuff than curl would
          normally do. You should not replace internally set  headers  without
          knowing  perfectly well what you're doing. Remove an internal header
          by giving a replacement without content on the  right  side  of  the
          colon, as in: -H "Host:".

          curl  will  make sure that each header you add/replace get sent with
          the proper end of line marker, you should thus not  add  that  as  a
          part  of the header content: do not add newlines or carriage returns
          they will only mess things up for you.

          See also the -A/--user-agent and -e/--referer options.

          This option can be used multiple times to add/replace/remove  multi-
          ple headers.

Example:

curl --header "X-MyHeader: 123" www.google.com

You can see the request that curl sent by adding the -v option.

Why can't I define a default constructor for a struct in .NET?

Just special-case it. If you see a numerator of 0 and a denominator of 0, pretend like it has the values you really want.

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

Android studio- "SDK tools directory is missing"

In case you are looking for Android SDK Manager, you can download it here.

It is important to unzip it as C:/Program Files/Android/. Launch the SDK manager by running C:/Program Files/Android/tools/android.bat administrator.

How to resize an image with OpenCV2.0 and Python2.6

Example doubling the image size

There are two ways to resize an image. The new size can be specified:

  1. Manually;

    height, width = src.shape[:2]

    dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)

  2. By a scaling factor.

    dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC), where fx is the scaling factor along the horizontal axis and fy along the vertical axis.

To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).

Example shrink image to fit a max height/width (keeping aspect ratio)

import cv2

img = cv2.imread('YOUR_PATH_TO_IMG')

height, width = img.shape[:2]
max_height = 300
max_width = 300

# only shrink if img is bigger than required
if max_height < height or max_width < width:
    # get scaling factor
    scaling_factor = max_height / float(height)
    if max_width/float(width) < scaling_factor:
        scaling_factor = max_width / float(width)
    # resize image
    img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)

cv2.imshow("Shrinked image", img)
key = cv2.waitKey()

Using your code with cv2

import cv2 as cv

im = cv.imread(path)

height, width = im.shape[:2]

thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)

cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()

MySQL Multiple Joins in one query?

Multi joins in SQL work by progressively creating derived tables one after the other. See this link explaining the process:

https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/

Show and hide divs at a specific time interval using jQuery

here is a jQuery plugin I came up with:

$.fn.cycle = function(timeout){
    var $all_elem = $(this)

    show_cycle_elem = function(index){
        if(index == $all_elem.length) return; //you can make it start-over, if you want
        $all_elem.hide().eq(index).fadeIn()
        setTimeout(function(){show_cycle_elem(++index)}, timeout);
    }
    show_cycle_elem(0);
}

You need to have a common classname for all the divs you wan to cycle, use it like this:

$("div.cycleme").cycle(5000)

How to get a path to the desktop for current user in C#?

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

If you open an editor and jump to the exact line shown in the error message (within the file httpd.conf), this is what you'd see:

#LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule auth_form_module modules/mod_auth_form.so

The paths to the modules, e.g. modules/mod_actions.so, are all stated relatively, and they are relative to the value set by ServerRoot. ServerRoot is defined at the top of httpd.conf (ctrl-F for ServerRoot ").

ServerRoot is usually set absolutely, which would be K:/../../../xampp/apache/ in your post.

But it can also be set relatively, relative to the working directory (cf.). If the working directory is the Apache bin folder, then use this line in your httpd.conf:

ServerRoot ../

If the working directory is the Apache folder, then this would suffice:

ServerRoot .

If the working directory is the C: folder (one folder above the Apache folder), then use this:

ServerRoot Apache

For apache services, the working directory would be C:\Windows\System32, so use this:

ServerRoot ../../Apache

get value from DataTable

You can try changing it to this:

If myTableData.Rows.Count > 0 Then
  For i As Integer = 0 To myTableData.Rows.Count - 1
    ''Dim DataType() As String = myTableData.Rows(i).Item(1)
    ListBox2.Items.Add(myTableData.Rows(i)(1))
  Next
End If

Note: Your loop needs to be one less than the row count since it's a zero-based index.

Editor does not contain a main type in Eclipse

Ideally, the source code file should go within the src/default package even if you haven't provided any package name. For some reason, the source file might be outside src folder. Create within the scr folder it will work!

Jquery $(this) Child Selector

This is a lot simpler with .slideToggle():

jQuery('.class1 a').click( function() {
  $(this).next('.class2').slideToggle();
});

EDIT: made it .next instead of .siblings

http://www.mredesign.com/demos/jquery-effects-1/

You can also add cookie's to remember where you're at...

http://c.hadcoleman.com/2008/09/jquery-slide-toggle-with-cookie/

How can we print line numbers to the log in java

The stackLevel depends on depth you call this method. You can try from 0 to a large number to see what difference.

If stackLevel is legal, you will get string like java.lang.Thread.getStackTrace(Thread.java:1536)

public static String getCodeLocationInfo(int stackLevel) {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        if (stackLevel < 0 || stackLevel >= stackTraceElements.length) {
            return "Stack Level Out Of StackTrace Bounds";
        }
        StackTraceElement stackTraceElement = stackTraceElements[stackLevel];
        String fullClassName = stackTraceElement.getClassName();
        String methodName = stackTraceElement.getMethodName();
        String fileName = stackTraceElement.getFileName();
        int lineNumber = stackTraceElement.getLineNumber();

        return String.format("%s.%s(%s:%s)", fullClassName, methodName, fileName, lineNumber);
}

Child inside parent with min-height: 100% not inheriting height

This is a reported webkit (chrome/safari) bug, children of parents with min-height can't inherit the height property: https://bugs.webkit.org/show_bug.cgi?id=26559

Apparently Firefox is affected too (can't test in IE at the moment)

Possible workaround:

  • add position:relative to #containment
  • add position:absolute to #containment-shadow-left

The bug doesn't show when the inner element has absolute positioning.

See http://jsfiddle.net/xrebB/

Edit on April 10, 2014

Since I'm currently working on a project for which I really need parent containers with min-height, and child elements inheriting the height of the container, I did some more research.

First: I'm not so sure anymore whether the current browser behaviour really is a bug. CSS2.1 specs say:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

If I put a min-height on my container, I'm not explicitly specifying its height - so my element should get an auto height. And that's exactly what Webkit - and all other browsers - do.

Second, the workaround I found:

If I set my container element to display:table with height:inherit it acts exactly the same way as if I'd give it a min-height of 100%. And - more importantly - if I set the child element to display:table-cell it will perfectly inherit the height of the container element - whether it's 100% or more.

Full CSS:

html, body {
  height: 100%;
  margin: 0;
}

#container {
  background: green;
  display: table;
  height: inherit;
  width: 100%;
}

#content {
  background: red;
  display: table-cell;
}

The markup:

<div id="container">
  <div id="content">
      <p>content</p>
  </div>
</div>

See http://jsfiddle.net/xrebB/54/.

jQuery.css() - marginLeft vs. margin-left?

when is marginLeft being used:

$("div").css({
    marginLeft:'12px',
    backgroundPosition:'10px -10px',
    minHeight: '40px'
});

As you can see, attributes that has a hyphen on it are converted to camelcased format. Using the margin-left from the previous code block above would make JavaScript bonkers because it will treat the hyphen as an operation for subtraction.

when is margin-left used:

$("div").css("margin-left","12px").css("background-position","10px -10px").css("min-height","40px");

Theoretically, both code blocks will do the same thing. We can allow hyphens on the second block because it is a string value while compared to the first block, it is somewhat an object.
Now that should make sense.

/usr/bin/codesign failed with exit code 1

There could be a lot of reason when you get this kind of error:

  1. Check whether you have selected a provisioning profile which includes the valid Code Signing Identity and a valid Bundle Identifier in Settings. (Goto Build Settings->Signing->Provisioning Profile).

  2. Open Keychain Access and click on lock icon at top left, so it will lock the login keychain and then again click to unlock.

enter image description here

  1. Goto File->Project Settings->Derived Data and delete your project build folder. After that clean and build your app.

"webxml attribute is required" error in Maven

It would be helpful if you can provide a code snippet of your maven-war-plugin. Looks like the web.xml is at right place, still you can try and give the location explicitly

<plugin>            
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <configuration>
    <webXml>src\main\webapp\WEB-INF\web.xml</webXml>        
  </configuration>
</plugin>

How can I specify a local gem in my Gemfile?

You can reference gems with source:

source: 'https://source.com', git repository (:github => 'git/url') and with local path

:path => '.../path/gem_name'.

You can learn more about [Gemfiles and how to use them] (https://kolosek.com/rails-bundle-install-and-gemfile) in this article.

Is it possible to open a Windows Explorer window from PowerShell?

$startinfo = new-object System.Diagnostics.ProcessStartInfo 
$startinfo.FileName = "explorer.exe"
$startinfo.WorkingDirectory = 'D:\foldername'

[System.Diagnostics.Process]::Start($startinfo)

Hope this helps

Any difference between await Promise.all() and multiple await?

In case of await Promise.all([task1(), task2()]); "task1()" and "task2()" will run parallel and will wait until both promises are completed (either resolved or rejected). Whereas in case of

const result1 = await t1;
const result2 = await t2;

t2 will only run after t1 has finished execution (has been resolved or rejected). Both t1 and t2 will not run parallel.

Why use HttpClient for Synchronous Connection

If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.

You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.

If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.

The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.

Difference between a SOAP message and a WSDL?

We need to define what is a web service before telling what are the difference between the SOAP and WSDL where the two (SOAP and WSDL) are components of a web service

Most applications are developed to interact with users, the user enters or searches for data through an interface and the application then responds to the user's input.

A Web service does more or less the same thing except that a Web service application communicates only from machine to machine or application to application. There is often no direct user interaction.

A Web service basically is a collection of open protocols that is used to exchange data between applications. The use of open protocols enables Web services to be platform independent. Software that are written in different programming languages and that run on different platforms can use Web services to exchange data over computer networks such as the Internet. In other words, Windows applications can talk to PHP, Java and Perl applications and many others, which in normal circumstances would not be possible.

How Do Web Services Work?

Because different applications are written in different programming languages, they often cannot communicate with each other. A Web service enables this communication by using a combination of open protocols and standards, chiefly XML, SOAP and WSDL. A Web service uses XML to tag data, SOAP to transfer a message and finally WSDL to describe the availability of services. Let's take a look at these three main components of a Web service application.

Simple Object Access Protocol (SOAP)

The Simple Object Access Protocol or SOAP is a protocol for sending and receiving messages between applications without confronting interoperability issues (interoperability meaning the platform that a Web service is running on becomes irrelevant). Another protocol that has a similar function is HTTP. It is used to access Web pages or to surf the Net. HTTP ensures that you do not have to worry about what kind of Web server -- whether Apache or IIS or any other -- serves you the pages you are viewing or whether the pages you view were created in ASP.NET or HTML.

Because SOAP is used both for requesting and responding, its contents vary slightly depending on its purpose.

Below is an example of a SOAP request and response message

SOAP Request:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPrice> 
    <m:BookName>The Fleamarket</m:BookName> 
    </m:GetBookPrice> 
</soap:Body> 
</soap:Envelope>

SOAP Response:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPriceResponse> 
    <m: Price>10.95</m: Price> 
    </m:GetBookPriceResponse> 
</soap:Body> 
</soap:Envelope> 

Although both messages look the same, they carry out different methods. For instance looking at the above examples you can see that the requesting message uses the GetBookPrice method to get the book price. The response is carried out by the GetBookPriceResponse method, which is going to be the message that you as the "requestor" will see. You can also see that the messages are composed using XML.

Web Services Description Language or WSDL

WSDL is a document that describes a Web service and also tells you how to access and use its methods.

WSDL takes care of how do you know what methods are available in a Web service that you stumble across on the Internet.

Take a look at a sample WSDL file:

<?xml version="1.0" encoding="UTF-8"?> 
<definitions  name ="DayOfWeek"  
  targetNamespace="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:tns="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"  
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns="http://schemas.xmlsoap.org/wsdl/">  
  <message name="DayOfWeekInput"> 
    <part name="date" type="xsd:date"/> 
  </message> 
  <message name="DayOfWeekResponse"> 
    <part name="dayOfWeek" type="xsd:string"/> 
  </message> 
  <portType name="DayOfWeekPortType"> 
    <operation name="GetDayOfWeek"> 
      <input message="tns:DayOfWeekInput"/> 
      <output message="tns:DayOfWeekResponse"/> 
    </operation> 
  </portType> 
  <binding name="DayOfWeekBinding" type="tns:DayOfWeekPortType"> 
    <soap:binding style="document"  
      transport="http://schemas.xmlsoap.org/soap/http"/> 
    <operation name="GetDayOfWeek"> 
      <soap:operation soapAction="getdayofweek"/> 
      <input> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"  
          encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </input> 
      <output> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"   
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </output> 
    </operation> 
  </binding> 
  <service name="DayOfWeekService" > 
    <documentation> 
      Returns the day-of-week name for a given date 
    </documentation> 
    <port name="DayOfWeekPort" binding="tns:DayOfWeekBinding"> 
      <soap:address location="http://localhost:8090/dayofweek/DayOfWeek"/> 
    </port> 
  </service> 
</definitions> 

The main things to remember about a WSDL file are that it provides you with:

  • A description of a Web service

  • The methods a Web service uses and the parameters that it takes

  • A way to locate Web services

  • Delete files or folder recursively on Windows CMD

    For completely wiping a folder with native commands and getting a log on what's been done.

    here's an unusual way to do it :

    let's assume we want to clear the d:\temp dir

    mkdir d:\empty
    robocopy /mir d:\empty d:\temp
    rmdir d:\empty
    

    How do MySQL indexes work?

    Take at this videos for more details about Indexing

    Simple Indexing You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table

    CREATE UNIQUE INDEX index_name
    ON table_name ( column1, column2,...);
    

    You can use one or more columns to create an index. For example, we can create an index on tutorials_tbl using tutorial_author.

    CREATE UNIQUE INDEX AUTHOR_INDEX
    ON tutorials_tbl (tutorial_author)
    

    You can create a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.

    If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name.

    mysql> CREATE UNIQUE INDEX AUTHOR_INDEX
    ON tutorials_tbl (tutorial_author DESC)
    

    JavaScript: Difference between .forEach() and .map()

    The main difference that you need to know is .map() returns a new array while .forEach() doesn't. That is why you see that difference in the output. .forEach() just operates on every value in the array.

    Read up:

    You might also want to check out: - Array.prototype.every() - JavaScript | MDN

    printf() formatting for hex

    The # part gives you a 0x in the output string. The 0 and the x count against your "8" characters listed in the 08 part. You need to ask for 10 characters if you want it to be the same.

    int i = 7;
    
    printf("%#010x\n", i);  // gives 0x00000007
    printf("0x%08x\n", i);  // gives 0x00000007
    printf("%#08x\n", i);   // gives 0x000007
    

    Also changing the case of x, affects the casing of the outputted characters.

    printf("%04x", 4779); // gives 12ab
    printf("%04X", 4779); // gives 12AB
    

    ImageView - have height match width?

    Update: Sep 14 2017

    According to a comment below, the percent support library is deprecated as of Android Support Library 26.0.0. This is the new way to do it:

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="1:1" />
    
    </android.support.constraint.ConstraintLayout>
    

    See here

    Deprecated:

    According to this post by Android Developers, all you need to do now is to wrap whatever you want within a PercentRelativeLayout or a PercentFrameLayout, and then specify its ratios, like so

    <android.support.percent.PercentRelativeLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <ImageView
            app:layout_widthPercent="100%"
            app:layout_aspectRatio="100%"/>
    
    </android.support.percent.PercentRelativeLayout>
    

    add an onclick event to a div

    Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

    Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

    If yes then why is the onclick method not going through to my div.

    You are assigning a string where a function is expected.

    divTag.onclick = printWorking;
    

    There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

    That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

    Oracle SQL query for Date format

    if you are using same date format and have select query where date in oracle :

       select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';
    

    To_DATE provided by oracle

    What's better at freeing memory with PHP: unset() or $var = null

    PHP 7 is already worked on such memory management issues and its reduced up-to minimal usage.

    <?php
      $start = microtime(true);
      for ($i = 0; $i < 10000000; $i++) {
        $a = 'a';
        $a = NULL;
      }
      $elapsed = microtime(true) - $start;
    
      echo "took $elapsed seconds\r\n";
    
      $start = microtime(true);
      for ($i = 0; $i < 10000000; $i++) {
         $a = 'a';
         unset($a);
      }
      $elapsed = microtime(true) - $start;
    
      echo "took $elapsed seconds\r\n";
    
    ?>
    

    PHP 7.1 Outpu:

    took 0.16778993606567 seconds took 0.16630101203918 seconds

    Java switch statement: Constant expression required, but it IS constant

    Below code is self-explanatory, We can use an enum with a switch case:

    /**
     *
     */
    enum ClassNames {
        STRING(String.class, String.class.getSimpleName()),
        BOOLEAN(Boolean.class, Boolean.class.getSimpleName()),
        INTEGER(Integer.class, Integer.class.getSimpleName()),
        LONG(Long.class, Long.class.getSimpleName());
        private Class typeName;
        private String simpleName;
        ClassNames(Class typeName, String simpleName){
            this.typeName = typeName;
            this.simpleName = simpleName;
        }
    }
    

    Based on the class values from the enum can be mapped:

     switch (ClassNames.valueOf(clazz.getSimpleName())) {
            case STRING:
                String castValue = (String) keyValue;
                break;
            case BOOLEAN:
                break;
            case Integer:
                break;
            case LONG:
                break;
            default:
                isValid = false;
    
        }
    

    Hope it helps :)

    What is the difference between os.path.basename() and os.path.dirname()?

    Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

    The os.path.dirname(path) function returns the head of the path.

    E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

    The os.path.basename(path) function returns the tail of the path.

    E.g.: The basename of '/foo/bar/item' returns 'item'

    From: http://docs.python.org/2/library/os.path.html#os.path.basename

    CSS display:table-row does not expand when width is set to 100%

    Note that according to the CSS3 spec, you do NOT have to wrap your layout in a table-style element. The browser will infer the existence of containing elements if they do not exist.

    Using Case/Switch and GetType to determine the object

    I'm faced with the same problem and came across this post. Is this what's meant by the IDictionary approach:

    Dictionary<Type, int> typeDict = new Dictionary<Type, int>
    {
        {typeof(int),0},
        {typeof(string),1},
        {typeof(MyClass),2}
    };
    
    void Foo(object o)
    {
        switch (typeDict[o.GetType()])
        {
            case 0:
                Print("I'm a number.");
                break;
            case 1:
                Print("I'm a text.");
                break;
            case 2:
                Print("I'm classy.");
                break;
            default:
                break;
        }
    }
    

    If so, I can't say I'm a fan of reconciling the numbers in the dictionary with the case statements.

    This would be ideal but the dictionary reference kills it:

    void FantasyFoo(object o)
    {
        switch (typeDict[o.GetType()])
        {
            case typeDict[typeof(int)]:
                Print("I'm a number.");
                break;
            case typeDict[typeof(string)]:
                Print("I'm a text.");
                break;
            case typeDict[typeof(MyClass)]:
                Print("I'm classy.");
                break;
            default:
                break;
        }
    }
    

    Is there another implementation I've overlooked?

    Android: adbd cannot run as root in production builds

    You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

    Getting the last revision number in SVN?

    svn info or svnversion won't take into consideration subdirectories, to find the latest 'revision' of the live codebase the hacked way below worked for me - it might take a while to run:

    repo_root$ find ./ | xargs -l svn info  | grep 'Revision: ' | sort
    ...
    Revision: 86
    Revision: 86
    Revision: 89
    Revision: 90
    $
    

    How to change background color in the Notepad++ text editor?

    There seems to have been an update some time in the past 3 years which changes the location of where to place themes in order to get them working.

    Previosuly, themes were located in the Notepad++ installation folder. Now they are located in AppData:

    C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes
    

    My answer is an update to @Amit-IO's answer about manually copying the themes.

    1. In Explorer, browse to: %AppData%\Notepad++.
    2. If a folder called themes does not exist, create it.
    3. Download your favourite theme from wherever (see Amit-IO's answer for a good list) and save it to %AppData%\Notepad++\themes.
    4. Restart Notepad++ and then use Settings -> Style Configurator. The new theme(s) will appear in the list.

    How can I easily convert DataReader to List<T>?

    You cant simply (directly) convert the datareader to list.

    You have to loop through all the elements in datareader and insert into list

    below the sample code

    using (drOutput)   
    {
                System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();        
                int customerId = drOutput.GetOrdinal("customerId ");
                int CustomerName = drOutput.GetOrdinal("CustomerName ");
    
            while (drOutput.Read())        
            {
                CustomerEntity obj=new CustomerEntity ();
                obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
                obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
                arrObjects .Add(obj);
            }
    
    }
    

    What is the difference between a generative and a discriminative algorithm?

    Imagine your task is to classify a speech to a language.

    You can do it by either:

    1. learning each language, and then classifying it using the knowledge you just gained

    or

    1. determining the difference in the linguistic models without learning the languages, and then classifying the speech.

    The first one is the generative approach and the second one is the discriminative approach.

    Check this reference for more details: http://www.cedar.buffalo.edu/~srihari/CSE574/Discriminative-Generative.pdf.

    Sort Go map values by keys

    The Go blog: Go maps in action has an excellent explanation.

    When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order.

    Here's my modified version of example code: http://play.golang.org/p/dvqcGPYy3-

    package main
    
    import (
        "fmt"
        "sort"
    )
    
    func main() {
        // To create a map as input
        m := make(map[int]string)
        m[1] = "a"
        m[2] = "c"
        m[0] = "b"
    
        // To store the keys in slice in sorted order
        keys := make([]int, len(m))
        i := 0
        for k := range m {
            keys[i] = k
            i++
        }
        sort.Ints(keys)
    
        // To perform the opertion you want
        for _, k := range keys {
            fmt.Println("Key:", k, "Value:", m[k])
        }
    }
    

    Output:

    Key: 0 Value: b
    Key: 1 Value: a
    Key: 2 Value: c
    

    How to create JSON post to api using C#

    Try using Web API HttpClient

        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://domain.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    
                // HTTP POST
                var obj = new MyObject() { Str = "MyString"};
                response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
                if (response.IsSuccessStatusCode)
                {
                    response.//.. Contains the returned content.
                }
            }
        }
    

    You can find more details here Web API Clients

    What's the fastest way to do a bulk insert into Postgres?

    I just encountered this issue and would recommend csvsql (releases) for bulk imports to Postgres. To perform a bulk insert you'd simply createdb and then use csvsql, which connects to your database and creates individual tables for an entire folder of CSVs.

    $ createdb test 
    $ csvsql --db postgresql:///test --insert examples/*.csv
    

    Chrome violation : [Violation] Handler took 83ms of runtime

    It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

    4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

    If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

    Is it possible to specify proxy credentials in your web.config?

    While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:

      <system.net>
        <defaultProxy useDefaultCredentials="true">
          <proxy proxyaddress="proxyAddress" usesystemdefault="True"/>
        </defaultProxy>
      </system.net>
    

    The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server. If your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.

    Eclipse interface icons very small on high resolution screen in Windows 8.1

    If you do not want to install a newer version of eclipse

    As mentioned here, in the eclipse.init file add -Dswt.autoScale=exact after the -vmargs and you are good to go.

    Here exact scales the icons to the native zoom. But you will have to adjust with the blurred and jagged icons.

    I need to round a float to two decimal places in Java

    If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:

    double d = 2.3d;
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    String output = formatter.format(d);
    

    Which will output (depending on locale):

    $2.30

    Also, if currency isn't required (just the exact two decimal places) you can use this instead:

    NumberFormat formatter = NumberFormat.getNumberInstance();
    formatter.setMinimumFractionDigits(2);
    formatter.setMaximumFractionDigits(2);
    String output = formatter.format(d);
    

    Which will output 2.30

    How to restart adb from root to user mode?

    I would like to add a little more explanation to @user837048's answer. on my OSX Yosemite and Galaxy S3 which is rooted and using firmware CyanogenMod 11 and KitKat I have done the below proceedings to Enable and Disable root prompt.

    Please make ensure below

    • On your system

      • Make sure you have installed Android SDK and you have set paths to binary files. type which adb on your shell. It must give you somewhat result. $ which adb /Applications/Android Studio.app/sdk/platform-tools/adb
    • On your Mobile

      • Settings > Developer Options> Android Debugging = ON
      • Settings > Developer Options> Root Access = Apps and ADB

    If you don't see Developer Options in your settings, Goto Settings > About Phone. Scroll down to Build number and tap there 7 times. I know its crazy. But believe me it works :D

    Connect your phone via USB Cable. type on your computer's terminal

    $ adb shell
    

    you will see a prompt similiar, If any prompt has been shown on your mobile, to trust the connection, tap 'Always Trust' and 'OK'

    shell@m0:/ $
    

    now type

    shell@m0:/ $ id
    uid=2000(shell) gid=2000(shell) groups=1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admin),3002(net_bt),3003(inet),3006(net_bw_stats) context=u:r:shell:s0
    

    See you are not root

    Now exit from shell, which will fall back to computer's prompt

    shell@m0:/ $ exit
    

    Now activate root

    $adb shell
    * daemon not running. starting it now on port 5037 *
    * daemon started successfully *
    root@m0:/ #
    

    Wow.. you are root

    root@m0:/ # id
    uid=0(root) gid=0(root) context=u:r:shell:s0
    

    I tried many solutions to go back to normal non root prompt. But didn't worked except @user837048's solution.

    root@m0:/ # stop adbd && setprop service.adb.root 0 && start adbd &
    [1] 32137
    root@m0:/ #
    $
    

    This might exit you from Adb prompt to normal prompt. Now connect again.

    $ adb shell
    shell@m0:/ $
    

    Well.. You are Non root

    There is already an object named in the database

    Delete rows from dbo_MigrationHistory table or delete the table and run

    update-database -verbose
    

    It will run all the migrations in your project one by one

    MySQL, update multiple tables with one query

    UPDATE t1
    INNER JOIN t2 ON t2.t1_id = t1.id
    INNER JOIN t3 ON t2.t3_id = t3.id
    SET t1.a = 'something',
        t2.b = 42,
        t3.c = t2.c
    WHERE t1.a = 'blah';
    

    To see what this is going to update, you can convert this into a select statement, e.g.:

    SELECT t2.t1_id, t2.t3_id, t1.a, t2.b, t2.c AS t2_c, t3.c AS t3_c
    FROM t1
    INNER JOIN t2 ON t2.t1_id = t1.id
    INNER JOIN t3 ON t2.t3_id = t3.id
    WHERE t1.a = 'blah';
    

    An example using the same tables as the other answer:

    SELECT Books.BookID, Orders.OrderID,
        Orders.Quantity AS CurrentQuantity,
        Orders.Quantity + 2 AS NewQuantity,
        Books.InStock AS CurrentStock,
        Books.InStock - 2 AS NewStock
    FROM Books
    INNER JOIN Orders ON Books.BookID = Orders.BookID
    WHERE Orders.OrderID = 1002;
    
    UPDATE Books
    INNER JOIN Orders ON Books.BookID = Orders.BookID
    SET Orders.Quantity = Orders.Quantity + 2,
        Books.InStock = Books.InStock - 2
    WHERE Orders.OrderID = 1002;
    

    EDIT:

    Just for fun, let's add something a bit more interesting.

    Let's say you have a table of books and a table of authors. Your books have an author_id. But when the database was originally created, no foreign key constraints were set up and later a bug in the front-end code caused some books to be added with invalid author_ids. As a DBA you don't want to have to go through all of these books to check what the author_id should be, so the decision is made that the data capturers will fix the books to point to the right authors. But there are too many books to go through each one and let's say you know that the ones that have an author_id that corresponds with an actual author are correct. It's just the ones that have nonexistent author_ids that are invalid. There is already an interface for the users to update the book details and the developers don't want to change that just for this problem. But the existing interface does an INNER JOIN authors, so all of the books with invalid authors are excluded.

    What you can do is this: Insert a fake author record like "Unknown author". Then update the author_id of all the bad records to point to the Unknown author. Then the data capturers can search for all books with the author set to "Unknown author", look up the correct author and fix them.

    How do you update all of the bad records to point to the Unknown author? Like this (assuming the Unknown author's author_id is 99999):

    UPDATE books
    LEFT OUTER JOIN authors ON books.author_id = authors.id
    SET books.author_id = 99999
    WHERE authors.id IS NULL;
    

    The above will also update books that have a NULL author_id to the Unknown author. If you don't want that, of course you can add AND books.author_id IS NOT NULL.

    Disable JavaScript error in WebBrowser control

    Here is an alternative solution:

    class extendedWebBrowser : WebBrowser
    {
        /// <summary>
        /// Default constructor which will make the browser to ignore all errors
        /// </summary>
        public extendedWebBrowser()
        {
            this.ScriptErrorsSuppressed = true;
    
            FieldInfo field = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (field != null)
            {
                 object axIWebBrowser2 = field.GetValue(this);
                 axIWebBrowser2.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, axIWebBrowser2, new object[] { true });
            }
        }
    }
    

    Nested attributes unpermitted parameters

    Today I came across this same issue, whilst working on rails 4, I was able to get it working by structuring my fields_for as:

    <%= f.select :tag_ids, Tag.all.collect {|t| [t.name, t.id]}, {}, :multiple => true %>
    

    Then in my controller I have my strong params as:

    private
    def post_params
        params.require(:post).permit(:id, :title, :content, :publish, tag_ids: [])
    end
    

    All works!

    How to escape JSON string?

    There's a Json library at Codeplex

    jquery - Check for file extension before uploading

    If you don't want to use $(this).val(), you can try:

    var file_onchange = function () {
      var input = this; // avoid using 'this' directly
    
      if (input.files && input.files[0]) {
        var type = input.files[0].type; // image/jpg, image/png, image/jpeg...
    
        // allow jpg, png, jpeg, bmp, gif, ico
        var type_reg = /^image\/(jpg|png|jpeg|bmp|gif|ico)$/;
    
        if (type_reg.test(type)) {
          // file is ready to upload
        } else {
          alert('This file type is unsupported.');
        }
      }
    };
    
    $('#file').on('change', file_onchange);
    

    Hope this helps!

    How to make an Android device vibrate? with different frequency?

    <uses-permission android:name="android.permission.VIBRATE"/>
    

    should be added inside <manifest> tag and outside <application> tag.

    PHP output showing little black diamonds with a question mark

    You can also change the caracter set in your browser. Just for debug reasons.

    Remove all multiple spaces in Javascript and replace with single space

    There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

    str.replace( /\s\s+/g, ' ' )
    

    See this question for a full discussion on this exact problem: Regex to replace multiple spaces with a single space

    Jackson overcoming underscores in favor of camel-case

    There are few answers here indicating both strategies for 2 different versions of Jackson library below:

    For Jackson 2.6.*

    ObjectMapper objMapper = new ObjectMapper(new JsonFactory()); // or YAMLFactory()
    objMapper.setNamingStrategy(
         PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    

    For Jackson 2.7.*

    ObjectMapper objMapper = new ObjectMapper(new JsonFactory()); // or YAMLFactory()
    objMapper.setNamingStrategy(
         PropertyNamingStrategy.SNAKE_CASE);
    

    Running Python code in Vim

    I use

    :! [filename.py]; python %
    

    That's what works for me

    angular 2 sort and filter

    A pipe takes in data as input and transforms it to a desired output. Add this pipe file:orderby.ts inside your /app folder .

    orderby.ts

    //The pipe class implements the PipeTransform interface's transform method that accepts an input value and an optional array of parameters and returns the transformed value.
    
    import { Pipe,PipeTransform } from "angular2/core";
    
    //We tell Angular that this is a pipe by applying the @Pipe decorator which we import from the core Angular library.
    
    @Pipe({
    
      //The @Pipe decorator takes an object with a name property whose value is the pipe name that we'll use within a template expression. It must be a valid JavaScript identifier. Our pipe's name is orderby.
    
      name: "orderby"
    })
    
    export class OrderByPipe implements PipeTransform {
      transform(array:Array<any>, args?) {
    
        // Check if array exists, in this case array contains articles and args is an array that has 1 element : !id
    
        if(array) {
    
          // get the first element
    
          let orderByValue = args[0]
          let byVal = 1
    
          // check if exclamation point 
    
          if(orderByValue.charAt(0) == "!") {
    
            // reverse the array
    
            byVal = -1
            orderByValue = orderByValue.substring(1)
          }
          console.log("byVal",byVal);
          console.log("orderByValue",orderByValue);
    
          array.sort((a: any, b: any) => {
            if(a[orderByValue] < b[orderByValue]) {
              return -1*byVal;
            } else if (a[orderByValue] > b[orderByValue]) {
              return 1*byVal;
            } else {
              return 0;
            }
          });
          return array;
        }
        //
      }
    }
    

    In your component file (app.component.ts) import the pipe that you just added using: import {OrderByPipe} from './orderby';

    Then, add *ngFor="#article of articles | orderby:'id'" inside your template if you want to sort your articles by id in ascending order or orderby:'!id'" in descending order.

    We add parameters to a pipe by following the pipe name with a colon ( : ) and then the parameter value

    We must list our pipe in the pipes array of the @Component decorator. pipes: [ OrderByPipe ] .

    app.component.ts

    import {Component, OnInit} from 'angular2/core';
    import {OrderByPipe} from './orderby';
    
    @Component({
        selector: 'my-app',
        template: `
          <h2>orderby-pipe by N2B</h2>
          <p *ngFor="#article of articles | orderby:'id'">
            Article title : {{article.title}}
          </p>
        `,
        pipes: [ OrderByPipe ]
    
    })
    export class AppComponent{
        articles:Array<any>
        ngOnInit(){
            this.articles = [
            {
                id: 1,
                title: "title1"
            },{
                id: 2,
                title: "title2",
            }]  
        }
    
    }
    

    More info here on my github and this post on my website

    'float' vs. 'double' precision

    Floating point numbers in C use IEEE 754 encoding.

    This type of encoding uses a sign, a significand, and an exponent.

    Because of this encoding, many numbers will have small changes to allow them to be stored.

    Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.

    Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.

    Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

    Select multiple value in DropDownList using ASP.NET and C#

    In that case you should use ListBox control instead of dropdown and Set the SelectionMode property to Multiple

    <asp:ListBox runat="server" SelectionMode="Multiple" >
      <asp:ListItem Text="test1"></asp:ListItem>
      <asp:ListItem Text="test2"></asp:ListItem>
      <asp:ListItem Text="test3"></asp:ListItem>
    </asp:ListBox>
    

    How do I apply the for-each loop to every character in a String?

    Unfortunately Java does not make String implement Iterable<Character>. This could easily be done. There is StringCharacterIterator but that doesn't even implement Iterator... So make your own:

    public class CharSequenceCharacterIterable implements Iterable<Character> {
        private CharSequence cs;
    
        public CharSequenceCharacterIterable(CharSequence cs) {
            this.cs = cs;
        }
    
        @Override
        public Iterator<Character> iterator() {
            return new Iterator<Character>() {
                private int index = 0;
    
                @Override
                public boolean hasNext() {
                    return index < cs.length();
                }
    
                @Override
                public Character next() {
                    return cs.charAt(index++);
                }
            };
        }
    }
    

    Now you can (somewhat) easily run for (char c : new CharSequenceCharacterIterable("xyz"))...

    In Java, what does NaN mean?

    Taken from this page:

    "NaN" stands for "not a number". "Nan" is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result. For example, 0.0 divided by 0.0 is arithmetically undefined. Taking the square root of a negative number is also undefined.

    Mongoose query where value is not null

    Ok guys I found a possible solution to this problem. I realized that joins do not exists in Mongo, that's why first you need to query the user's ids with the role you like, and after that do another query to the profiles document, something like this:

        const exclude: string = '-_id -created_at -gallery -wallet -MaxRequestersPerBooking -active -__v';
    
      // Get the _ids of users with the role equal to role.
        await User.find({role: role}, {_id: 1, role: 1, name: 1},  function(err, docs) {
    
            // Map the docs into an array of just the _ids
            var ids = docs.map(function(doc) { return doc._id; });
    
            // Get the profiles whose users are in that set.
            Profile.find({user: {$in: ids}}, function(err, profiles) {
                // docs contains your answer
                res.json({
                    code: 200,
                    profiles: profiles,
                    page: page
                })
            })
            .select(exclude)
            .populate({
                path: 'user',
                select: '-password -verified -_id -__v'
                // group: { role: "$role"} 
              })
        });
    

    Typescript: Type 'string | undefined' is not assignable to type 'string'

    You can use the NonNullable Utility Type:

    Example

    type T0 = NonNullable<string | number | undefined>;  // string | number
    type T1 = NonNullable<string[] | null | undefined>;  // string[]
    

    Docs.

    How to recover MySQL database from .myd, .myi, .frm files

    Note that if you want to rebuild the MYI file then the correct use of REPAIR TABLE is:

    REPAIR TABLE sometable USE_FRM;

    Otherwise you will probably just get another error.

    HTML5 tag for horizontal line break

    Simply use hr tag in HTML file and add below code in CSS file .

        hr {
           display: block;
           position: relative;
           padding: 0;
           margin: 8px auto;
           height: 0;
           width: 100%;
           max-height: 0;
           font-size: 1px;
           line-height: 0;
           clear: both;
           border: none;
           border-top: 1px solid #aaaaaa;
           border-bottom: 1px solid #ffffff;
        }
    

    it works perfectly .

    Taking the record with the max date

    If date and col_date are the same columns you should simply do:

    SELECT A, MAX(date) FROM t GROUP BY A
    

    Why not use:

    WITH x AS ( SELECT A, MAX(col_date) m FROM TABLENAME )
    SELECT A, date FROM TABLENAME t JOIN x ON x.A = t.A AND x.m = t.col_date
    

    Otherwise:

    SELECT A, FIRST_VALUE(date) KEEP(dense_rank FIRST ORDER BY col_date DESC)
      FROM TABLENAME
     GROUP BY A
    

    Fetch first element which matches criteria

    When you write a lambda expression, the argument list to the left of -> can be either a parenthesized argument list (possibly empty), or a single identifier without any parentheses. But in the second form, the identifier cannot be declared with a type name. Thus:

    this.stops.stream().filter(Stop s-> s.getStation().getName().equals(name));
    

    is incorrect syntax; but

    this.stops.stream().filter((Stop s)-> s.getStation().getName().equals(name));
    

    is correct. Or:

    this.stops.stream().filter(s -> s.getStation().getName().equals(name));
    

    is also correct if the compiler has enough information to figure out the types.

    How can I find last row that contains data in a specific column?

    Sub test()
        MsgBox Worksheets("sheet_name").Range("A65536").End(xlUp).Row
    End Sub
    

    This is looking for a value in column A because of "A65536".

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

    As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com

    This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).

    How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

    The query below will result in dd/mm/yy format.

    select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)
    

    Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

    Run this script from SharePoint 2010 Management Shell as Administrator.

    400 vs 422 response to POST of data

    Your case: HTTP 400 is the right status code for your case from REST perspective as its syntactically incorrect to send sales_tax instead of tax, though its a valid JSON. This is normally enforced by most of the server side frameworks when mapping the JSON to objects. However, there are some REST implementations that ignore new key in JSON object. In that case, a custom content-type specification to accept only valid fields can be enforced by server-side.

    Ideal Scenario for 422:

    In an ideal world, 422 is preferred and generally acceptable to send as response if the server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the data because its semantically erroneous.

    Situations of 400 over 422:

    Remember, the response code 422 is an extended HTTP (WebDAV) status code. There are still some HTTP clients / front-end libraries that aren't prepared to handle 422. For them, its as simple as "HTTP 422 is wrong, because it's not HTTP". From the service perspective, 400 isn't quite specific.

    In enterprise architecture, the services are deployed mostly on service layers like SOA, IDM, etc. They typically serve multiple clients ranging from a very old native client to a latest HTTP clients. If one of the clients doesn't handle HTTP 422, the options are that asking the client to upgrade or change your response code to HTTP 400 for everyone. In my experience, this is very rare these days but still a possibility. So, a careful study of your architecture is always required before deciding on the HTTP response codes.

    To handle situation like these, the service layers normally use versioning or setup configuration flag for strict HTTP conformance clients to send 400, and send 422 for the rest of them. That way they provide backwards compatibility support for existing consumers but at the same time provide the ability for the new clients to consume HTTP 422.


    The latest update to RFC7321 says:

    The 400 (Bad Request) status code indicates that the server cannot or
       will not process the request due to something that is perceived to be
       a client error (e.g., malformed request syntax, invalid request
       message framing, or deceptive request routing).
    

    This confirms that servers can send HTTP 400 for invalid request. 400 doesn't refer only to syntax error anymore, however, 422 is still a genuine response provided the clients can handle it.

    Raise error in a Bash script

    Basic error handling

    If your test case runner returns a non-zero code for failed tests, you can simply write:

    test_handler test_case_x; test_result=$?
    if ((test_result != 0)); then
      printf '%s\n' "Test case x failed" >&2  # write error message to stderr
      exit 1                                  # or exit $test_result
    fi
    

    Or even shorter:

    if ! test_handler test_case_x; then
      printf '%s\n' "Test case x failed" >&2
      exit 1
    fi
    

    Or the shortest:

    test_handler test_case_x || { printf '%s\n' "Test case x failed" >&2; exit 1; }
    

    To exit with test_handler's exit code:

    test_handler test_case_x || { ec=$?; printf '%s\n' "Test case x failed" >&2; exit $ec; }
    

    Advanced error handling

    If you want to take a more comprehensive approach, you can have an error handler:

    exit_if_error() {
      local exit_code=$1
      shift
      [[ $exit_code ]] &&               # do nothing if no error code passed
        ((exit_code != 0)) && {         # do nothing if error code is 0
          printf 'ERROR: %s\n' "$@" >&2 # we can use better logging here
          exit "$exit_code"             # we could also check to make sure
                                        # error code is numeric when passed
        }
    }
    

    then invoke it after running your test case:

    run_test_case test_case_x
    exit_if_error $? "Test case x failed"
    

    or

    run_test_case test_case_x || exit_if_error $? "Test case x failed"
    

    The advantages of having an error handler like exit_if_error are:

    • we can standardize all the error handling logic such as logging, printing a stack trace, notification, doing cleanup etc., in one place
    • by making the error handler get the error code as an argument, we can spare the caller from the clutter of if blocks that test exit codes for errors
    • if we have a signal handler (using trap), we can invoke the error handler from there

    Error handling and logging library

    Here is a complete implementation of error handling and logging:

    https://github.com/codeforester/base/blob/master/lib/stdlib.sh


    Related posts

    How to connect html pages to mysql database?

    HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

    Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

    So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

    Now, lets see a snippet of connection using MYSQLi Extension of PHP

    $db = mysqli_connect('hostname','username','password','databasename');
    

    This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

    <?php
        $db = mysqli_connect('hostname','username','password','databasename');
    ?>
    <html>
        <body>
              <?php
                    $query = "SELECT * FROM `mytable`;";
                    $result = mysqli_query($db, $query);
                    while($row = mysqli_fetch_assoc($result)) {
                          // Display your datas on the page
                    }
              ?>
        </body>
    </html>
    

    In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

    How are iloc and loc different?

    iloc works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing

    df.iloc[0]
    

    or the last five rows by doing

    df.iloc[-5:]
    

    You can also use it on the columns. This retrieves the 3rd column:

    df.iloc[:, 2]    # the : in the first position indicates all rows
    

    You can combine them to get intersections of rows and columns:

    df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)
    

    On the other hand, .loc use named indices. Let's set up a data frame with strings as row and column labels:

    df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])
    

    Then we can get the first row by

    df.loc['a']     # equivalent to df.iloc[0]
    

    and the second two rows of the 'date' column by

    df.loc['b':, 'date']   # equivalent to df.iloc[1:, 1]
    

    and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame are integers from 0 and in this case iloc and loc would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5] would raise an error.

    Also, you can do column retrieval just by using the data frame's __getitem__:

    df['time']    # equivalent to df.loc[:, 'time']
    

    Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix comes in:

    df.ix[:2, 'time']    # the first two rows of the 'time' column
    

    I think it's also worth mentioning that you can pass boolean vectors to the loc method as well. For example:

     b = [True, False, True]
     df.loc[b] 
    

    Will return the 1st and 3rd rows of df. This is equivalent to df[b] for selection, but it can also be used for assigning via boolean vectors:

    df.loc[b, 'name'] = 'Mary', 'John'
    

    How to get the next auto-increment id in mysql

    If return no correct AUTO_INCREMENT, try it:

    ANALYZE TABLE `my_table`;
    SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE (TABLE_NAME = 'my_table');
    

    This clear cache for table, in BD

    Executing a shell script from a PHP script

    Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.

    For A Debian box with Apache and sudo:

    1. Configure sudo:

      • As root, run the following to edit a new/dedicated configuration file for sudo:

        visudo -f /etc/sudoers.d/Webserver
        

        (or whatever you want to call your file in /etc/sudoers.d/)

      • Add the following to the file:

        www-data ALL = (root) NOPASSWD: <executable_file_path>
        

        where <executable_file_path> is the command that you need to be able to run as root with the full path in its name(say /bin/chown for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.

        For example, say we always want to copy the same file in the /root/ directory, we would write the following:

        www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
        
    2. Modify the script(testscript):

      Edit your script such that sudo appears before the command that requires root privileges(say sudo /bin/chown ... or sudo /bin/cp /root/test1 /root/test2). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file. So, for our example above, we would have the following in the script:

      sudo /bin/cp /root/test1 /root/test2
      

    If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.

    Keep in mind:

    When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).

    KeyListener, keyPressed versus keyTyped

    private String message;
    private ScreenManager s;
    
    
    //Here is an example of code to add the keyListener() as suggested; modify 
    public void init(){
    Window w = s.getFullScreenWindow();
    w.addKeyListener(this);
    
    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
            if(keyCode == KeyEvent.VK_F5)
                message = "Pressed: " + KeyEvent.getKeyText(keyCode);
    }
    

    Python decorators in classes

    I have a Implementation of Decorators that Might Help

        import functools
        import datetime
    
    
        class Decorator(object):
    
            def __init__(self):
                pass
    
    
            def execution_time(func):
    
                @functools.wraps(func)
                def wrap(self, *args, **kwargs):
    
                    """ Wrapper Function """
    
                    start = datetime.datetime.now()
                    Tem = func(self, *args, **kwargs)
                    end = datetime.datetime.now()
                    print("Exection Time:{}".format(end-start))
                    return Tem
    
                return wrap
    
    
        class Test(Decorator):
    
            def __init__(self):
                self._MethodName = Test.funca.__name__
    
            @Decorator.execution_time
            def funca(self):
                print("Running Function : {}".format(self._MethodName))
                return True
    
    
        if __name__ == "__main__":
            obj = Test()
            data = obj.funca()
            print(data)
    

    Find and Replace Inside a Text File from a Bash Command

    I found this thread among others and I agree it contains the most complete answers so I'm adding mine too:

    1. sed and ed are so useful...by hand. Look at this code from @Johnny:

      sed -i -e 's/abc/XYZ/g' /tmp/file.txt
      
    2. When my restriction is to use it in a shell script, no variable can be used inside in place of "abc" or "XYZ". The BashFAQ seems to agree with what I understand at least. So, I can't use:

      x='abc'
      y='XYZ'
      sed -i -e 's/$x/$y/g' /tmp/file.txt
      #or,
      sed -i -e "s/$x/$y/g" /tmp/file.txt
      

      but, what can we do? As, @Johnny said use a while read... but, unfortunately that's not the end of the story. The following worked well with me:

      #edit user's virtual domain
      result=
      #if nullglob is set then, unset it temporarily
      is_nullglob=$( shopt -s | egrep -i '*nullglob' )
      if [[ is_nullglob ]]; then
         shopt -u nullglob
      fi
      while IFS= read -r line; do
         line="${line//'<servername>'/$server}"
         line="${line//'<serveralias>'/$alias}"
         line="${line//'<user>'/$user}"
         line="${line//'<group>'/$group}"
         result="$result""$line"'\n'
      done < $tmp
      echo -e $result > $tmp
      #if nullglob was set then, re-enable it
      if [[ is_nullglob ]]; then
         shopt -s nullglob
      fi
      #move user's virtual domain to Apache 2 domain directory
      ......
      
    3. As one can see if nullglob is set then, it behaves strangely when there is a string containing a * as in:

      <VirtualHost *:80>
       ServerName www.example.com
      

      which becomes

      <VirtualHost ServerName www.example.com
      

      there is no ending angle bracket and Apache2 can't even load.

    4. This kind of parsing should be slower than one-hit search and replace but, as you already saw, there are four variables for four different search patterns working out of one parse cycle.

    The most suitable solution I can think of with the given assumptions of the problem.

    jQuery: Check if div with certain class name exists

    In Jquery you can use like this.

    if ($(".className")[0]){
    
       // Do something if class exists
    
    } else {
    
    // Do something if class does not exist
    
    }
    

    With JavaScript

    if (document.getElementsByClassName("className").length > 0) {
    
    // Do something if class exists
    
    }else{
    
        // Do something if class does not exist......
    
    }
    

    How to compare DateTime without time via LINQ?

    Try

    var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);
    

    OS X Terminal shortcut: Jump to beginning/end of line

    In the latest Mac OS You can use shift + home or shift + end

    Understanding the set() function

    After reading the other answers, I still had trouble understanding why the set comes out un-ordered.

    Mentioned this to my partner and he came up with this metaphor: take marbles. You put them in a tube a tad wider than marble width : you have a list. A set, however, is a bag. Even though you feed the marbles one-by-one into the bag; when you pour them from a bag back into the tube, they will not be in the same order (because they got all mixed up in a bag).

    HTTPS setup in Amazon EC2

    An old question but worth mentioning another option in the answers. In case the DNS system of your domain has been defined in Amazon Route 53, you can use Amazon CloudFront service in front of your EC2 and attach a free Amazon SSL certificate to it. This way you will benefit from both having a CDN for a faster content delivery and also securing you domain with HTTPS protocol.

    MySQL Error 1093 - Can't specify target table for update in FROM clause

    DELETE FROM story_category
    WHERE category_id NOT IN (
        SELECT cid FROM (
            SELECT DISTINCT category.id AS cid FROM category INNER JOIN story_category ON category_id=category.id
        ) AS c
    )
    

    Laravel 5 Clear Views Cache

    To answer your additional question how disable views caching:

    You can do this by automatically delete the files in the folder for each request with the command php artisan view:clear mentioned by DilipGurung. Here is an example Middleware class from https://stackoverflow.com/a/38598434/2311074

    <?php
    namespace App\Http\Middleware;
    
    use Artisan;
    use Closure;
    
    class ClearViewCache
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if (env('APP_DEBUG') || env('APP_ENV') === 'local') 
                Artisan::call('view:clear');
    
            return $next($request);
        }
    }
    

    However you may note that Larevel will recompile the files in the /app/storage/views folder whenever the time on the views files is earlier than the time on the PHP blade files for the layout. THus, I cannot really think of a scenario where this would be necessary to do.

    White space at top of page

    overflow: auto

    Using overflow: auto on the <body> tag is a cleaner solution and will work a charm.

    Recursive sub folder search and return files in a list python

    Recursive is new in Python 3.5, so it won't work on Python 2.7. Here is the example that uses r strings so you just need to provide the path as is on either Win, Lin, ...

    import glob
    
    mypath=r"C:\Users\dj\Desktop\nba"
    
    files = glob.glob(mypath + r'\**\*.py', recursive=True)
    # print(files) # as list
    for f in files:
        print(f) # nice looking single line per file
    

    Note: It will list all files, no matter how deep it should go.

    ldap_bind: Invalid Credentials (49)

    I don't see an obvious problem with the above.

    It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

    Try an explicit URI:

    ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
    

    or prevent defaults with:

    LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
    

    If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

    • make sure your slapd.conf is being used and is correct (as root)

      slapd -T test -f slapd.conf -d 65535

      You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

    • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

      slapd -h ldap://localhost -d 481

      then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

    • if debug is enabled, then try also

      ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

    string encoding and decoding?

    Aside from getting decode and encode backwards, I think part of the answer here is actually don't use the ascii encoding. It's probably not what you want.

    To begin with, think of str like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.

    Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.

    The problem is that in practice, you run into both. Some libraries give you a str, and some expect a str. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.

    Enter codecs: it's the translation library between these two data types. You use encode to generate a sequence of bytes (str) from a text string (unicode), and you use decode to get a text string (unicode) from a sequence of bytes (str).

    For example:

    >>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
    >>> codecs.decode(s, 'utf-8')
    u"I look like a string, but I'm actually a sequence of bytes. \u2764"
    

    What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode version of this, given that this sequence of bytes is in 'utf-8'." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.

    Let's go the other way around:

    >>> u = u"I'm a string! Really! \u2764"
    >>> codecs.encode(u, 'utf-8')
    "I'm a string! Really! \xe2\x9d\xa4"
    

    I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8' encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.

    We can work with other encodings, too, of course:

    >>> s = "I have a section \xa7"
    >>> codecs.decode(s, 'latin1')
    u'I have a section \xa7'
    >>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
    True
    
    >>> u = u"I have a section \u00a7"
    >>> u
    u'I have a section \xa7'
    >>> codecs.encode(u, 'latin1')
    'I have a section \xa7'
    

    ('\xa7' is the section character, in both Unicode and Latin-1.)

    So for your question, you first need to figure out what encoding your str is in.

    • Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode.

      s = [get from external source]
      u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
      
    • Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str. UTF-8 is a good choice for plain text documents; most things can read it.

      u = u'My string'
      s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
      [Write s out somewhere]
      
    • Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8' is probably the best choice for that:

      u = u'My string'
      s = codecs.encode(u, 'utf-8')
      newu = codecs.decode(s, 'utf-8')
      

    In modern programming, you probably never want to use the 'ascii' encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.

    Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str was replaced with bytes, and unicode was replaced with str.

    Merging arrays with the same keys

    $arr1 = array(
       "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
       "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
       "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
       "3" => array("fid" => 1, "tid" => 7, "name" => "Xi"),
       "4" => array("fid" => 2, "tid" => 9, "name" => "Xigua")
    );
    

    if you want to convert this array as following:

    $arr2 = array(
       "0" => array(
              "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
              "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
              "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
              "3" => array("fid" => 1, "tid" => 7, "name" => "Xi")
        ),
    
        "1" => array(
              "0" =>array("fid" => 2, "tid" => 9, "name" => "Xigua")
         )
    );
    

    so, my answer will be like this:

    $outer_array = array();
    $unique_array = array();
    foreach($arr1 as $key => $value)
    {
        $inner_array = array();
    
        $fid_value = $value['fid'];
        if(!in_array($value['fid'], $unique_array))
        {
                array_push($unique_array, $fid_value);
                unset($value['fid']);
                array_push($inner_array, $value);
                $outer_array[$fid_value] = $inner_array;
    
    
        }else{
                unset($value['fid']);
                array_push($outer_array[$fid_value], $value);
    
        }
    }
    var_dump(array_values($outer_array));
    

    hope this answer will help somebody sometime.

    How do I change the default port (9000) that Play uses when I execute the "run" command?

    We cannot change the application port from the avtivator but can change from the command line activator "~run 8080"

    But to run on the poet 9000 from the activator we need to stop the application which is using this port. We can use the this application to find this and end the process https://technet.microsoft.com/en-in/sysinternals/bb897437.aspx

    After this we can run and it will be successful.

    Map a 2D array onto a 1D array

    Example : we want to represent an 2D array of SIZE_X and SIZE_Y size. That means that we will have MAXY consecutive rows of MAXX size. Hence the set function is

    void set_array( int x, int y, int val ) { array[ x * SIZE_Y + y ] = val; }
    

    The get would be:

    int get_array( int x, int y ) { return array[ x * SIZE_Y + y ]; }
    

    Splitting applicationContext to multiple files

    @eljenso : intrafest-servlet.xml webapplication context xml will be used if the application uses SPRING WEB MVC.

    Otherwise the @kosoant configuration is fine.

    Simple example if you dont use SPRING WEB MVC, but want to utitlize SPRING IOC :

    In web.xml:

    <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:application-context.xml</param-value>
    </context-param>
    

    Then, your application-context.xml will contain: <import resource="foo-services.xml"/> these import statements to load various application context files and put into main application-context.xml.

    Thanks and hope this helps.

    Is it valid to replace http:// with // in a <script src="http://...">?

    The pattern I see on html5-boilerplate is:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
    

    It runs smoothly on different schemes like http, https, file.

    python setup.py uninstall

    The #1 answer has problems:

    • Won't work on mac.
    • If a file is installed which includes spaces or other special characters, the xargs command will fail, and delete any files/directories which matched the individual words.
    • the -r in rm -rf is unnecessary and at worst could delete things you don't want to.

    Instead, for unix-like:

    sudo python setup.py install --record files.txt
    # inspect files.txt to make sure it looks ok. Then:
    tr '\n' '\0' < files.txt | xargs -0 sudo rm -f --
    

    And for windows:

    python setup.py bdist_wininst
    dist/foo-1.0.win32.exe
    

    There are also unsolvable problems with uninstalling setup.py install which won't bother you in a typical case. For a more complete answer, see this wiki page:

    https://ofswiki.org/wiki/Uninstalling_setup.py_install

    How to remove the first character of string in PHP?

    you can use the sbstr() function

    $amount = 1;   //where $amount the amount of string you want to delete starting  from index 0
    $str = substr($str, $amount);
    

    Set background image on grid in WPF using C#

    Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.

    <Grid>
        <Grid.Background>
            <ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
        </Grid.Background>
    
        <...>
    </Grid>
    

    No generated R.java file in my project

    This could also be the problem of an incorrect xml layout file for example. If your xml files are not valid (containing errors) the R file will not re-generate after a clean-up. If you fix this, the R file will be generated automatically again.

    Run class in Jar file

    You want:

    java -cp myJar.jar myClass
    

    The Documentation gives the following example:

    C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool
    

    How to copy JavaScript object to new variable NOT by reference?

    Your only option is to somehow clone the object.

    See this stackoverflow question on how you can achieve this.

    For simple JSON objects, the simplest way would be:

    var newObject = JSON.parse(JSON.stringify(oldObject));
    

    if you use jQuery, you can use:

    // Shallow copy
    var newObject = jQuery.extend({}, oldObject);
    
    // Deep copy
    var newObject = jQuery.extend(true, {}, oldObject);
    

    UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

    In ES6 or TypeScript (2.1+):

    var shallowCopy = { ...oldObject };
    
    var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };
    

    Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

    How to Cast Objects in PHP

    a better aproach:

    class Animal
    {
        private $_name = null;
    
        public function __construct($name = null)
        {
            $this->_name = $name;
        }
    
        /**
         * casts object
         * @param Animal $to
         * @return Animal
         */
        public function cast($to)
        {
            if ($to instanceof Animal) {
                $to->_name = $this->_name;
            } else {
                throw(new Exception('cant cast ' . get_class($this) . ' to ' . get_class($to)));
            return $to;
        }
    
        public function getName()
        {
            return $this->_name;
        }
    }
    
    class Cat extends Animal
    {
        private $_preferedKindOfFish = null;
    
        public function __construct($name = null, $preferedKindOfFish = null)
        {
            parent::__construct($name);
            $this->_preferedKindOfFish = $preferedKindOfFish;
        }
    
        /**
         * casts object
         * @param Animal $to
         * @return Animal
         */
        public function cast($to)
        {
            parent::cast($to);
            if ($to instanceof Cat) {
                $to->_preferedKindOfFish = $this->_preferedKindOfFish;
            }
            return $to;
        }
    
        public function getPreferedKindOfFish()
        {
            return $this->_preferedKindOfFish;
        }
    }
    
    class Dog extends Animal
    {
        private $_preferedKindOfCat = null;
    
        public function __construct($name = null, $preferedKindOfCat = null)
        {
            parent::__construct($name);
            $this->_preferedKindOfCat = $preferedKindOfCat;
        }
    
        /**
         * casts object
         * @param Animal $to
         * @return Animal
         */
        public function cast($to)
        {
            parent::cast($to);
            if ($to instanceof Dog) {
                $to->_preferedKindOfCat = $this->_preferedKindOfCat;
            }
            return $to;
        }
    
        public function getPreferedKindOfCat()
        {
            return $this->_preferedKindOfCat;
        }
    }
    
    $dogs = array(
        new Dog('snoopy', 'vegetarian'),
        new Dog('coyote', 'any'),
    );
    
    foreach ($dogs as $dog) {
        $cat = $dog->cast(new Cat());
        echo get_class($cat) . ' - ' . $cat->getName() . "\n";
    }
    

    This declaration has no storage class or type specifier in C++

    Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

    How to create a custom-shaped bitmap marker with Android map API v2

    The alternative and easier solution that i also use is to create custom marker layout and convert it into a bitmap.

    view_custom_marker.xml

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/custom_marker_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/marker_mask">
    
        <ImageView
            android:id="@+id/profile_image"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_gravity="center_horizontal"
            android:contentDescription="@null"
            android:src="@drawable/avatar" />
    </FrameLayout>
    

    Convert this view into bitmap by using the code below

     private Bitmap getMarkerBitmapFromView(@DrawableRes int resId) {
    
            View customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
            ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.profile_image);
            markerImageView.setImageResource(resId);
            customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
            customMarkerView.buildDrawingCache();
            Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(returnedBitmap);
            canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
            Drawable drawable = customMarkerView.getBackground();
            if (drawable != null)
                drawable.draw(canvas);
            customMarkerView.draw(canvas);
            return returnedBitmap;
        }
    

    Add your custom marker in on Map ready callback.

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Log.d(TAG, "onMapReady() called with");
        mGoogleMap = googleMap;
        MapsInitializer.initialize(this);
        addCustomMarker();
    }
    private void addCustomMarker() {
        Log.d(TAG, "addCustomMarker()");
        if (mGoogleMap == null) {
            return;
        }
    
        // adding a marker on map with image from  drawable
       mGoogleMap.addMarker(new MarkerOptions()
                .position(mDummyLatLng)
                .icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(R.drawable.avatar))));
    }
    

    For more details please follow the link below

    How to create custom marker using layout?

    Django CharField vs TextField

    It's a difference between RDBMS's varchar (or similar) — those are usually specified with a maximum length, and might be more efficient in terms of performance or storage — and text (or similar) types — those are usually limited only by hardcoded implementation limits (not a DB schema).

    PostgreSQL 9, specifically, states that "There is no performance difference among these three types", but AFAIK there are some differences in e.g. MySQL, so this is something to keep in mind.

    A good rule of thumb is that you use CharField when you need to limit the maximum length, TextField otherwise.

    This is not really Django-specific, also.

    There was no endpoint listening at (url) that could accept the message

    I tried a bunch of these ideas to get HTTPS working, but the key for me was adding the protocol mapping. Here's what my server config file looks like, this works for both HTTP and HTTPS client connections:

      <system.serviceModel>
        <protocolMapping>
          <add scheme="https" binding="wsHttpBinding" bindingConfiguration="TransportSecurityBinding" />
        </protocolMapping>
        <services>
          <service name="FeatureService" behaviorConfiguration="HttpsBehavior">
            <endpoint address="soap" binding="wsHttpBinding" contract="MyServices.IFeature" bindingConfiguration="TransportSecurityBinding" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="HttpsBehavior">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
            <behavior name="">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <bindings>
          <wsHttpBinding>
            <binding name="TransportSecurityBinding" maxReceivedMessageSize="2147483647">
              <security mode="Transport">
                <transport clientCredentialType="None" />
              </security>
            </binding>
          </wsHttpBinding>
        </bindings>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
    

    Call an overridden method from super class in typescript

    The order of execution is:

    1. A's constructor
    2. B's constructor

    The assignment occurs in B's constructor after A's constructor—_super—has been called:

    function B() {
        _super.apply(this, arguments);   // MyvirtualMethod called in here
        this.testString = "Test String"; // testString assigned here
    }
    

    So the following happens:

    var b = new B();     // undefined
    b.MyvirtualMethod(); // "Test String"
    

    You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod() in B's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A's constructor and working that out somehow... there's lots of possibilities.

    How to remove old and unused Docker images

    If you wish to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the image meltwater/docker-cleanup.

    Just run:

    docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw  -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest
    

    It runs every 30 minutes by default. You can however set the delay time by using this flag in seconds (DELAY_TIME=1800 option).

    More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md

    Is there a way to create key-value pairs in Bash script?

    In bash version 4 associative arrays were introduced.

    declare -A arr
    
    arr["key1"]=val1
    
    arr+=( ["key2"]=val2 ["key3"]=val3 )
    

    The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.

    for key in ${!arr[@]}; do
        echo ${key} ${arr[${key}]}
    done
    

    Will loop over all key values and echo them out.

    Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here

    PHP is_numeric or preg_match 0-9 validation

    PHP's is_numeric function allows for floats as well as integers. At the same time, the is_int function is too strict if you want to validate form data (strings only). Therefore, you had usually best use regular expressions for this.

    Strictly speaking, integers are whole numbers positive and negative, and also including zero. Here is a regular expression for this:

    /^0$|^[-]?[1-9][0-9]*$/

    OR, if you want to allow leading zeros:

    /^[-]?[0]|[1-9][0-9]$/

    Note that this will allow for values such as -0000, which does not cause problems in PHP, however. (MySQL will also cast such values as 0.)

    You may also want to confine the length of your integer for considerations of 32/64-bit PHP platform features and/or database compatibility. For instance, to limit the length of your integer to 9 digits (excluding the optional - sign), you could use:

    /^0$|^[-]?[1-9][0-9]{0,8}$/

    How to search if dictionary value contains certain string with Python

    import json 'mtach' in json.dumps(myDict) is true if found

    How to force a UIViewController to Portrait orientation in iOS 6

    The best way for iOS6 specifically is noted in "iOS6 By Tutorials" by the Ray Wenderlich team - http://www.raywenderlich.com/ and is better than subclassing UINavigationController for most cases.

    I'm using iOS6 with a storyboard that includes a UINavigationController set as the initial view controller.

    //AppDelegate.m - this method is not available pre-iOS6 unfortunately

    - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    NSUInteger orientations = UIInterfaceOrientationMaskAllButUpsideDown;
    
    if(self.window.rootViewController){
        UIViewController *presentedViewController = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
        orientations = [presentedViewController supportedInterfaceOrientations];
    }
    
    return orientations;
    }
    

    //MyViewController.m - return whatever orientations you want to support for each UIViewController

    - (NSUInteger)supportedInterfaceOrientations{
        return UIInterfaceOrientationMaskPortrait;
    }
    

    Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

    @article = user.articles.build(:title => "MainTitle")
    @article.save
    

    PHP foreach loop through multidimensional array

    <?php
    $php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
    
    //Iterate through an array declared above
    
    foreach($php_multi_array as $key => $value)
    {
        if (!is_array($value))
        {
            echo $key ." => ". $value ."\r\n" ;
        }
        else
        {
           echo $key ." => array( \r\n";
    
           foreach ($value as $key2 => $value2)
           {
               echo "\t". $key2 ." => ". $value2 ."\r\n";
           }
    
           echo ")";
        }
    }
    ?>
    

    OUTPUT:

    lang => PHP
    type => array( 
        c_type => MULTI
        p_type => ARRAY
    )
    

    Reference Source Code

    String.equals versus ==

    equals() function is a method of Object class which should be overridden by programmer. String class overrides it to check if two strings are equal i.e. in content and not reference.

    == operator checks if the references of both the objects are the same.

    Consider the programs

    String abc = "Awesome" ;
    String xyz =  abc;
    
    if(abc == xyz)
         System.out.println("Refers to same string");
    

    Here the abc and xyz, both refer to same String "Awesome". Hence the expression (abc == xyz) is true.

    String abc = "Hello World";
    String xyz = "Hello World";
    
    if(abc == xyz)
        System.out.println("Refers to same string");
    else
        System.out.println("Refers to different strings");
    
    if(abc.equals(xyz))
         System.out.prinln("Contents of both strings are same");
    else
         System.out.prinln("Contents of strings are different");
    

    Here abc and xyz are two different strings with the same content "Hello World". Hence here the expression (abc == xyz) is false where as (abc.equals(xyz)) is true.

    Hope you understood the difference between == and <Object>.equals()

    Thanks.

    Error: free(): invalid next size (fast):

    I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it. So, if the same case, better allocate some memory using resize() and then access vector elements.

    No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

    There are two ways to fix the problem.

    Way 1:

    Add spring.jackson.serialization.fail-on-empty-beans=false into application.properties

    Way 2:

    Use join fetch in JPQL query to retrieve parent object data, see below:

    @Query(value = "select child from Child child join fetch child.parent Parent ",
               countQuery = "select count(*) from Child child join child.parent parent ")
    public Page<Parent> findAll(Pageable pageable); 
    

    IN vs ANY operator in PostgreSQL

    (Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

    Logically, quoting the manual:

    IN is equivalent to = ANY.

    But there are two syntax variants of IN and two variants of ANY. Details:

    IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

    But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

    ANY is more versatile

    The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

    SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');
    

    For a big number of values, providing a set scales better for each:

    Related:

    Inversion / opposite / exclusion

    "Find rows where id is in the given array":

    SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);
    

    Inversion: "Find rows where id is not in the array":

    SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
    SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
    SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));
    

    All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

    Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

    SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;
    

    string to string array conversion in java

    String strName = "name";
    String[] strArray = new String[] {strName};
    System.out.println(strArray[0]); //prints "name"
    

    The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:

    String[] strArray = new String[1];
    

    instead, the length is determined by the number of elements in the initalizer. Using

    String[] strArray = new String[] {strName, "name1", "name2"};
    

    creates an array with a length of 3.

    SQL datetime format to date only

    try the following as there will be no varchar conversion

    SELECT Subject, CAST(DeliveryDate AS DATE)
    from Email_Administration 
    where MerchantId =@ MerchantID
    

    Use tab to indent in textarea

    Here's my version of this, supports:

    • tab + shift tab
    • maintains undo stack for simple tab character inserts
    • supports block line indent/unindent but trashes undo stack
    • properly selects whole lines when block indent/unindent
    • supports auto indent on pressing enter (maintains undo stack)
    • use Escape key cancel support on next tab/enter key (so you can press Escape then tab out)
    • Works on Chrome + Edge, untested others.

    _x000D_
    _x000D_
    $(function() { _x000D_
     var enabled = true;_x000D_
     $("textarea.tabSupport").keydown(function(e) {_x000D_
    _x000D_
      // Escape key toggles tab on/off_x000D_
      if (e.keyCode==27)_x000D_
      {_x000D_
       enabled = !enabled;_x000D_
       return false;_x000D_
      }_x000D_
    _x000D_
      // Enter Key?_x000D_
      if (e.keyCode === 13 && enabled)_x000D_
      {_x000D_
       // selection?_x000D_
       if (this.selectionStart == this.selectionEnd)_x000D_
       {_x000D_
        // find start of the current line_x000D_
        var sel = this.selectionStart;_x000D_
        var text = $(this).val();_x000D_
        while (sel > 0 && text[sel-1] != '\n')_x000D_
        sel--;_x000D_
    _x000D_
        var lineStart = sel;_x000D_
        while (text[sel] == ' ' || text[sel]=='\t')_x000D_
        sel++;_x000D_
    _x000D_
        if (sel > lineStart)_x000D_
        {_x000D_
         // Insert carriage return and indented text_x000D_
         document.execCommand('insertText', false, "\n" + text.substr(lineStart, sel-lineStart));_x000D_
    _x000D_
         // Scroll caret visible_x000D_
         this.blur();_x000D_
         this.focus();_x000D_
         return false;_x000D_
        }_x000D_
       }_x000D_
      }_x000D_
    _x000D_
      // Tab key?_x000D_
      if(e.keyCode === 9 && enabled) _x000D_
      {_x000D_
       // selection?_x000D_
       if (this.selectionStart == this.selectionEnd)_x000D_
       {_x000D_
        // These single character operations are undoable_x000D_
        if (!e.shiftKey)_x000D_
        {_x000D_
         document.execCommand('insertText', false, "\t");_x000D_
        }_x000D_
        else_x000D_
        {_x000D_
         var text = this.value;_x000D_
         if (this.selectionStart > 0 && text[this.selectionStart-1]=='\t')_x000D_
         {_x000D_
          document.execCommand('delete');_x000D_
         }_x000D_
        }_x000D_
       }_x000D_
       else_x000D_
       {_x000D_
        // Block indent/unindent trashes undo stack._x000D_
        // Select whole lines_x000D_
        var selStart = this.selectionStart;_x000D_
        var selEnd = this.selectionEnd;_x000D_
        var text = $(this).val();_x000D_
        while (selStart > 0 && text[selStart-1] != '\n')_x000D_
         selStart--;_x000D_
        while (selEnd > 0 && text[selEnd-1]!='\n' && selEnd < text.length)_x000D_
         selEnd++;_x000D_
    _x000D_
        // Get selected text_x000D_
        var lines = text.substr(selStart, selEnd - selStart).split('\n');_x000D_
    _x000D_
        // Insert tabs_x000D_
        for (var i=0; i<lines.length; i++)_x000D_
        {_x000D_
         // Don't indent last line if cursor at start of line_x000D_
         if (i==lines.length-1 && lines[i].length==0)_x000D_
          continue;_x000D_
    _x000D_
         // Tab or Shift+Tab?_x000D_
         if (e.shiftKey)_x000D_
         {_x000D_
          if (lines[i].startsWith('\t'))_x000D_
           lines[i] = lines[i].substr(1);_x000D_
          else if (lines[i].startsWith("    "))_x000D_
           lines[i] = lines[i].substr(4);_x000D_
         }_x000D_
         else_x000D_
          lines[i] = "\t" + lines[i];_x000D_
        }_x000D_
        lines = lines.join('\n');_x000D_
    _x000D_
        // Update the text area_x000D_
        this.value = text.substr(0, selStart) + lines + text.substr(selEnd);_x000D_
        this.selectionStart = selStart;_x000D_
        this.selectionEnd = selStart + lines.length; _x000D_
       }_x000D_
    _x000D_
       return false;_x000D_
      }_x000D_
    _x000D_
      enabled = true;_x000D_
      return true;_x000D_
     });_x000D_
    });
    _x000D_
    textarea_x000D_
    {_x000D_
      width: 100%;_x000D_
      height: 100px;_x000D_
      tab-size: 4;_x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <textarea class="tabSupport">if (something)_x000D_
    {_x000D_
     // This textarea has "tabSupport" CSS style_x000D_
     // Try using tab key_x000D_
     // Try selecting multiple lines and using tab and shift+tab_x000D_
     // Try pressing enter at end of this line for auto indent_x000D_
     // Use Escape key to toggle tab support on/off_x000D_
     //     eg: press Escape then Tab to go to next field_x000D_
    }_x000D_
    </textarea>_x000D_
    <textarea>This text area doesn't have tabSupport class so disabled here</textarea>
    _x000D_
    _x000D_
    _x000D_

    Docker Compose wait for container X before starting Y

    In version 3 of a Docker Compose file, you can use RESTART.

    For example:

    docker-compose.yml

    worker:
        build: myapp/.
        volumes:
        - myapp/.:/usr/src/app:ro
        restart: on-failure
        depends_on:
        - rabbitmq
    rabbitmq:
        image: rabbitmq:3-management
    

    Note that I used depends_on instead of links since the latter is deprecated in version 3.

    Even though it works, it might not be the ideal solution since you restart the docker container at every failure.

    Have a look to RESTART_POLICY as well. it let you fine tune the restart policy.

    When you use Compose in production, it is actually best practice to use the restart policy :

    Specifying a restart policy like restart: always to avoid downtime

    HTML img scaling

    Adding max-width: 100%; to the img tag works for me.

    How to change the cursor into a hand when a user hovers over a list item?

    just using CSS to set customize the cursor pointer

    
    /* Keyword value */
    cursor: pointer;
    cursor: auto;
    
    /* URL, with a keyword fallback */
    cursor: url(hand.cur), pointer;
    
    /* URL and coordinates, with a keyword fallback */
    cursor: url(cursor1.png) 4 12, auto;
    cursor: url(cursor2.png) 2 2, pointer;
    
    /* Global values */
    cursor: inherit;
    cursor: initial;
    cursor: unset;
    
    
    /* 2 URLs and coordinates, with a keyword fallback */
    
    cursor: url(one.svg) 2 2, url(two.svg) 5 5, progress;
    
    

    demo

    Note: cursor support for many format icons!

    such as .cur, .png, .svg, .jpeg, .webp, and so on

    _x000D_
    _x000D_
    li:hover{
      cursor: url("https://cdn.xgqfrms.xyz/cursor/mouse.cur"), pointer;
      color: #0f0;
      background: #000;
    }
    
    
    /*
    
    li:hover{
      cursor: url("../icons/hand.cur"), pointer;
    }
    
    */
    
    li{
      height: 30px;
      width: 100px;
      background: #ccc;
      color: #fff;
      margin: 10px;
      text-align: center;
      list-style: none;
    }
    _x000D_
    <ul>
      <li>a</li>
      <li>b</li>
      <li>c</li>
    </ul>
    _x000D_
    _x000D_
    _x000D_

    refs

    https://developer.mozilla.org/en-US/docs/Web/CSS/cursor

    curl_exec() always returns false

    This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

    It took me a couple hours to finally understand the diference in the characters bellow:

    https://www.e-example.com/api
    https://www.e-example.com/api
    

    Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

    It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

    Hope this helps someone.

    PHP, get file name without file extension

    No need for all that. Check out pathinfo(), it gives you all the components of your path.

    Example from the manual:

    $path_parts = pathinfo('/www/htdocs/index.html');
    
    echo $path_parts['dirname'], "\n";
    echo $path_parts['basename'], "\n";
    echo $path_parts['extension'], "\n";
    echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0
    

    Output of the code:

    /www/htdocs
    index.html
    html
    index
    

    And alternatively you can get only certain parts like:

    echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html
    

    How does HTTP_USER_AGENT work?

    The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

    Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

    Make a VStack fill the width of the screen in SwiftUI

    With Swift 5.2 and iOS 13.4, according to your needs, you can use one of the following examples to align your VStack with top leading constraints and a full size frame.

    Note that the code snippets below all result in the same display, but do not guarantee the effective frame of the VStack nor the number of View elements that might appear while debugging the view hierarchy.


    1. Using frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:) method

    The simplest approach is to set the frame of your VStack with maximum width and height and also pass the required alignment in frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:):

    struct ContentView: View {
    
        var body: some View {
            VStack(alignment: .leading) {
                Text("Title")
                    .font(.title)
                Text("Content")
                    .font(.body)
            }
            .frame(
                maxWidth: .infinity,
                maxHeight: .infinity,
                alignment: .topLeading
            )
            .background(Color.red)
        }
    
    }
    

    As an alternative, if setting maximum frame with specific alignment for your Views is a common pattern in your code base, you can create an extension method on View for it:

    extension View {
    
        func fullSize(alignment: Alignment = .center) -> some View {
            self.frame(
                maxWidth: .infinity,
                maxHeight: .infinity,
                alignment: alignment
            )
        }
    
    }
    
    struct ContentView : View {
    
        var body: some View {
            VStack(alignment: .leading) {
                Text("Title")
                    .font(.title)
                Text("Content")
                    .font(.body)
            }
            .fullSize(alignment: .topLeading)
            .background(Color.red)
        }
    
    }
    

    2. Using Spacers to force alignment

    You can embed your VStack inside a full size HStack and use trailing and bottom Spacers to force your VStack top leading alignment:

    struct ContentView: View {
    
        var body: some View {
            HStack {
                VStack(alignment: .leading) {
                    Text("Title")
                        .font(.title)
                    Text("Content")
                        .font(.body)
    
                    Spacer() // VStack bottom spacer
                }
    
                Spacer() // HStack trailing spacer
            }
            .frame(
                maxWidth: .infinity,
                maxHeight: .infinity
            )
            .background(Color.red)
        }
    
    }
    

    3. Using a ZStack and a full size background View

    This example shows how to embed your VStack inside a ZStack that has a top leading alignment. Note how the Color view is used to set maximum width and height:

    struct ContentView: View {
    
        var body: some View {
            ZStack(alignment: .topLeading) {
                Color.red
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
    
                VStack(alignment: .leading) {
                    Text("Title")
                        .font(.title)
                    Text("Content")
                        .font(.body)
                }
            }
        }
    
    }
    

    4. Using GeometryReader

    GeometryReader has the following declaration:

    A container view that defines its content as a function of its own size and coordinate space. [...] This view returns a flexible preferred size to its parent layout.

    The code snippet below shows how to use GeometryReader to align your VStack with top leading constraints and a full size frame:

    struct ContentView : View {
    
        var body: some View {
            GeometryReader { geometryProxy in
                VStack(alignment: .leading) {
                    Text("Title")
                        .font(.title)
                    Text("Content")
                        .font(.body)
                }
                .frame(
                    width: geometryProxy.size.width,
                    height: geometryProxy.size.height,
                    alignment: .topLeading
                )
            }
            .background(Color.red)
        }
    
    }
    

    5. Using overlay(_:alignment:) method

    If you want to align your VStack with top leading constraints on top of an existing full size View, you can use overlay(_:alignment:) method:

    struct ContentView: View {
    
        var body: some View {
            Color.red
                .frame(
                    maxWidth: .infinity,
                    maxHeight: .infinity
                )
                .overlay(
                    VStack(alignment: .leading) {
                        Text("Title")
                            .font(.title)
                        Text("Content")
                            .font(.body)
                    },
                    alignment: .topLeading
                )
        }
    
    }
    

    Display:

    Force DOM redraw/refresh on Chrome/Mac

    I wanted to return all the states to the previous state (without reloading) including the elements added by jquery. The above implementation not gonna works. and I did as follows.

    // Set initial HTML description
    var defaultHTML;
    function DefaultSave() {
      defaultHTML = document.body.innerHTML;
    }
    // Restore HTML description to initial state
    function HTMLRestore() {
      document.body.innerHTML = defaultHTML;
    }
    
    
    
    DefaultSave()
    <input type="button" value="Restore" onclick="HTMLRestore()">
    

    `getchar()` gives the same output as the input string

    In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

    How to pass json POST data to Web API method as an object?

    Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.

    Here is my JavaScript (using AngluarJS):

    $scope.updateUserActivity = function (_objuserActivity) {
            $http
            ({
                method: 'post',
                url: 'your url here',
                headers: { 'Content-Type': 'application/json'},
                data: JSON.stringify(_objuserActivity)
            })
            .then(function (response)
            {
                alert("success");
            })
            .catch(function (response)
            {
                alert("failure");
            })
            .finally(function ()
            {
            });
    

    And here is my WebAPI Controller:

    [HttpPost]
    [AcceptVerbs("POST")]
    public string POSTMe([FromBody]Models.UserActivity _activity)
    {
        return "hello";
    }
    

    Escaping backslash in string - javascript

    Add an input id to the element and do something like that:

    document.getElementById('inputId').value.split(/[\\$]/).pop()
    

    Create space at the beginning of a UITextField

    To create padding view for UITextField in Swift 5

    func txtPaddingVw(txt:UITextField) {
        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
        txt.leftViewMode = .always
        txt.leftView = paddingView
    }
    

    Why is nginx responding to any domain name?

    You should have a default server for catch-all, you can return 404 or better to not respond at all (will save some bandwidth) by returning 444 which is nginx specific HTTP response that simply close the connection and return nothing

    server {
        listen       80  default_server;
        server_name  _; # some invalid name that won't match anything
        return       444;
    }