Programs & Examples On #Data security

How can I update the current line in a C# Windows Console App?

You can use the \b (backspace) escape sequence to backup a particular number of characters on the current line. This just moves the current location, it does not remove the characters.

For example:

string line="";

for(int i=0; i<100; i++)
{
    string backup=new string('\b',line.Length);
    Console.Write(backup);
    line=string.Format("{0}%",i);
    Console.Write(line);
}

Here, line is the percentage line to write to the console. The trick is to generate the correct number of \b characters for the previous output.

The advantage of this over the \r approach is that if works even if your percentage output is not at the beginning of the line.

Using only CSS, show div on hover over <a>

The + allow 'select' only first not nested element , the > select nested elements only - the better is to use ~ which allow to select arbitrary element which is child of parent hovered element. Using opacity/width and transition you can provide smooth appear

_x000D_
_x000D_
div { transition: all 1s }_x000D_
.ccc, .ggg { opacity: 0; color: red}_x000D_
.ccc { height: 0 }_x000D_
_x000D_
.aaa:hover ~ .bbb .ccc { opacity: 1; height: 34px }_x000D_
.aaa:hover ~ .eee .fff .ggg { opacity: 1 }
_x000D_
<div class="aaa">Hover me... to see<br><br> </div>_x000D_
_x000D_
<div class='bbb'>BBBBB_x000D_
  <div class='ccc'>CCCCC_x000D_
    <div class='ddd'>DDDDD</div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class='eee'>EEEEE_x000D_
  <div class='fff'>FFFFF_x000D_
    <div class='ggg'>GGGGG</div>_x000D_
    <div class='hhh'>HHHHH</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I convert a org.w3c.dom.Document object to a String?

A Scala version based on Zaz's answer.

  case class DocumentEx(document: Document) {
    def toXmlString(pretty: Boolean = false):Try[String] = {
      getStringFromDocument(document, pretty)
    }
  }

  implicit def documentToDocumentEx(document: Document):DocumentEx = {
    DocumentEx(document)
  }

  def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
    try
    {
      val domSource= new DOMSource(doc)
      val writer = new StringWriter()
      val result = new StreamResult(writer)
      val tf = TransformerFactory.newInstance()
      val transformer = tf.newTransformer()
      if (pretty)
        transformer.setOutputProperty(OutputKeys.INDENT, "yes")
      transformer.transform(domSource, result)
      Success(writer.toString);
    }
    catch {
      case ex: TransformerException =>
        Failure(ex)
    }
  }

With that, you can do either doc.toXmlString() or call the getStringFromDocument(doc) function.

SQLAlchemy equivalent to SQL "LIKE" statement

If you use native sql, you can refer to my code, otherwise just ignore my answer.

SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text

bar_tags = "banana"

# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""

# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()

PHP Get all subdirectories of a given directory

You can use the glob() function to do this.

Here is some documentation on it: http://php.net/manual/en/function.glob.php

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Shouldn't you have:

DELETE FROM tableA WHERE entitynum IN (...your select...)

Now you just have a WHERE with no comparison:

DELETE FROM tableA WHERE (...your select...)

So your final query would look like this;

DELETE FROM tableA WHERE entitynum IN (
    SELECT tableA.entitynum FROM tableA q
      INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
    WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
      AND (u.FldFormat = 'Date')
)

CSS Inset Borders

You can do this:

.thing {
  border: 2px solid transparent;
}
.thing:hover {
  border: 2px solid green;
}

What's "this" in JavaScript onclick?

keyword this in addEventListener event

_x000D_
_x000D_
function getValue(o) {_x000D_
  alert(o.innerHTML);_x000D_
}_x000D_
_x000D_
function hide(current) {_x000D_
  current.setAttribute("style", "display: none");_x000D_
}_x000D_
_x000D_
var bullet = document.querySelectorAll(".bullet");_x000D_
_x000D_
for (var x in bullet) { _x000D_
  bullet[x].onclick = function() {_x000D_
    hide(this);_x000D_
  };_x000D_
};_x000D_
 _x000D_
/* Using dynamic DOM Event */_x000D_
document.querySelector("#li").addEventListener("click", function() {_x000D_
  getValue(this); /* this = document.querySelector("#li") Object */_x000D_
});
_x000D_
li {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<ul>_x000D_
  <li onclick="getValue(this);">A</li>_x000D_
  <li id="li" >B</li>_x000D_
  <hr />_x000D_
  <li class="bullet" >1</li>_x000D_
  <li class="bullet" >2</li>_x000D_
  <li class="bullet" >3</li>_x000D_
  <li class="bullet" >4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

How to express a NOT IN query with ActiveRecord/Rails?

This way optimizes for readability, but it's not as efficient in terms of database queries:

# Retrieve all topics, then use array subtraction to
# find the ones not in our list
Topic.all - @forums.map(&:id)

Determine a user's timezone

There's no such way to figure the timezone in the actual HTML code or any user-agent string, but what you can do is make a basic function getting it using JavaScript.

I don't know how to code with JavaScript yet so my function might take time to make.

However, you can try to get the actual timezone also using JavaScript with the getTzimezoneOffset() function in the Date section or simply new Date().getTimezoneOffset();.

Sending message through WhatsApp

The following code is used by Google Now App and will NOT work for any other application.

I'm writing this post because it makes me angry, that WhatsApp does not allow any other developers to send messages directly except for Google.

And I want other freelance-developers to know, that this kind of cooperation is going on, while Google keeps talking about "open for anybody" and WhatsApp says they don't want to provide any access to developers.

Recently WhatsApp has added an Intent specially for Google Now, which should look like following:

Intent intent = new Intent("com.google.android.voicesearch.SEND_MESSAGE_TO_CONTACTS");
intent.setPackage("com.whatsapp");
intent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.VoiceMessagingActivity"));

intent.putExtra("com.google.android.voicesearch.extra.RECIPIENT_CONTACT_CHAT_ID", number);
intent.putExtra("android.intent.extra.TEXT", text);
intent.putExtra("search_action_token", ?????);

I could also find out that "search_action_token" is a PendingIntent that contains an IBinder-Object, which is sent back to Google App and checked, if it was created by Google Now.

Otherwise WhatsApp will not accept the message.

How do I change the formatting of numbers on an axis with ggplot?

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)

ActionBarActivity: cannot be resolved to a type

There is a mistake in your 'andrroid-sdk' folder. You selected some features while creating new project which need some components to import. It is needed to download a special android library and place it in android-sdk folder. For me it works fine: 1-Create a folder with name extras in your android-sdk folder 2-Create a folder with name android in extras 3-Download this file.(In my case I need this library) 4-Unzip it and copy the content (support folder) in the current android folder 5-close Eclipse and start it again 6-create your project again

I hope it to work for you.

Convert a float64 to an int in Go

Simply casting to an int truncates the float, which if your system internally represent 2.0 as 1.9999999999, you will not get what you expect. The various printf conversions deal with this and properly round the number when converting. So to get a more accurate value, the conversion is even more complicated than you might first expect:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    floats := []float64{1.9999, 2.0001, 2.0}
    for _, f := range floats {
        t := int(f)
        s := fmt.Sprintf("%.0f", f)
        if i, err := strconv.Atoi(s); err == nil {
            fmt.Println(f, t, i)
        } else {
            fmt.Println(f, t, err)
        }
    }
}

Code on Go Playground

How to sort a list/tuple of lists/tuples by the element at a given index?

Without lambda:

def sec_elem(s):
    return s[1]

sorted(data, key=sec_elem)

How can I make a CSS table fit the screen width?

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Change to another USB port works for me. I tried reset ADB, but problem still there.

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

Get spinner selected items text?

spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {

            String selected_val=spinner_button.getSelectedItem().toString();

            Toast.makeText(getApplicationContext(), selected_val ,
                    Toast.LENGTH_SHORT).show();
        }

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

        }
    });

}

How to repair a serialized string which has been corrupted by an incorrect byte count length?

Another reason of this problem can be column type of "payload" sessions table. If you have huge data on session, a text column wouldn't be enough. You will need MEDIUMTEXT or even LONGTEXT.

Update TextView Every Second

You can use Timer instead of Thread. This is whole my code

package dk.tellwork.tellworklite.tabs;

import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import dk.tellwork.tellworklite.MainActivity;
import dk.tellwork.tellworklite.R;

@SuppressLint("HandlerLeak")
public class HomeActivity extends Activity {
    Button chooseYourAcitivity, startBtn, stopBtn;
    TextView labelTimer;
    int passedSenconds;
    Boolean isActivityRunning = false;
    Timer timer;
    TimerTask timerTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_home);

        chooseYourAcitivity = (Button) findViewById(R.id.btnChooseYourActivity);
        chooseYourAcitivity.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //move to Activities tab
                switchTabInActivity(1);
            }
        });

        labelTimer = (TextView)findViewById(R.id.labelTime);
        passedSenconds = 0;

        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (isActivityRunning) {
                    //pause running activity
                    timer.cancel();
                    startBtn.setText(getString(R.string.homeStartBtn));
                    isActivityRunning = false;
                } else {
                    reScheduleTimer();
                    startBtn.setText(getString(R.string.homePauseBtn));
                    isActivityRunning = true;
                }
            }
        });

        stopBtn = (Button)findViewById(R.id.stopBtn);
        stopBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                timer.cancel();
                passedSenconds = 0;
                labelTimer.setText("00 : 00 : 00");
                startBtn.setText(getString(R.string.homeStartBtn));
                isActivityRunning = false;
            }
        });
    }

    public void reScheduleTimer(){
        timer = new Timer();
        timerTask = new myTimerTask();
        timer.schedule(timerTask, 0, 1000);
    }

    private class myTimerTask extends TimerTask{
        @Override
        public void run() {
            // TODO Auto-generated method stub
            passedSenconds++;
            updateLabel.sendEmptyMessage(0);
        }
    }

    private Handler updateLabel = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            //super.handleMessage(msg);

            int seconds = passedSenconds % 60;
            int minutes = (passedSenconds / 60) % 60;
            int hours = (passedSenconds / 3600);
            labelTimer.setText(String.format("%02d : %02d : %02d", hours, minutes, seconds));
        }
    };

    public void switchTabInActivity(int indexTabToSwitchTo){
        MainActivity parentActivity;
        parentActivity = (MainActivity) this.getParent();
        parentActivity.switchTab(indexTabToSwitchTo);
    }
}

ng-repeat: access key and value for each object in array of objects

In case this is an option for you, if you put your data into object form it works the way I think you're hoping for:

$scope.steps = {
 companyName: true,
 businessType: true,
 physicalAddress: true
};

Here's a fiddle of this: http://jsfiddle.net/zMjVp/

getApplication() vs. getApplicationContext()

To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.

Getting content/message from HttpResponseMessage

Try this, you can create an extension method like this:

    public static string ContentToString(this HttpContent httpContent)
    {
        var readAsStringAsync = httpContent.ReadAsStringAsync();
        return readAsStringAsync.Result;
    }

and then, simple call the extension method:

txtBlock.Text = response.Content.ContentToString();

I hope this help you ;-)

Create a new file in git bash

Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.

git add does not create any files. See also http://gitref.org/basic/#add

Github probably creates the file with touch and adds the file for tracking automatically. You can do this on the bash as well.

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

How do I create a pause/wait function using Qt?

I've had a lot of trouble over the years trying to get QApplication::processEvents to work, as is used in some of the top answers. IIRC, if multiple locations end up calling it, it can end up causing some signals to not get processed (https://doc.qt.io/archives/qq/qq27-responsive-guis.html). My usual preferred option is to utilize a QEventLoop (https://doc.qt.io/archives/qq/qq27-responsive-guis.html#waitinginalocaleventloop).

inline void delay(int millisecondsWait)
{
    QEventLoop loop;
    QTimer t;
    t.connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
    t.start(millisecondsWait);
    loop.exec();
}

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

PostgreSQL: role is not permitted to log in

try to run

sudo su - postgres
psql
ALTER ROLE 'dbname'

How do you read from stdin?

There's a few ways to do it.

  • sys.stdin is a file-like object on which you can call functions read or readlines if you want to read everything or you want to read everything and split it by newline automatically. (You need to import sys for this to work.)

  • If you want to prompt the user for input, you can use raw_input in Python 2.X, and just input in Python 3.

  • If you actually just want to read command-line options, you can access them via the sys.argv list.

You will probably find this Wikibook article on I/O in Python to be a useful reference as well.

Why do you have to link the math library in C?

Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.

An implementation where all functions are in one library and the -lm, -lpthread, -lrt, etc. options are all no-ops (or link to empty .a files) is perfectly POSIX conformant and certainly preferable.

Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm as the implementation-specific way the compiler must be invoked for conformant behavior.

React Checkbox not sending onChange

onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.

<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;

pip install from git repo branch

Prepend the url prefix git+ (See VCS Support):

pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6

And specify the branch name without the leading /.

How to convert int to date in SQL Server 2008

You can't convert an integer value straight to a date but you can first it to a datetime then to a date type

select cast(40835 as datetime)

and then convert to a date (SQL 2008)

select cast(cast(40835 as datetime) as date)

cheers

How do I determine if a checkbox is checked?

Place the var lfckv inside the function. When that line is executed, the body isn't parsed yet and the element "lifecheck" doesn't exist. This works perfectly fine:

_x000D_
_x000D_
function exefunction() {_x000D_
  var lfckv = document.getElementById("lifecheck").checked;_x000D_
  alert(lfckv);_x000D_
}
_x000D_
<label><input id="lifecheck" type="checkbox" >Lives</label>_x000D_
<button onclick="exefunction()">Check value</button>
_x000D_
_x000D_
_x000D_

Coarse-grained vs fine-grained

In the terms of POS (Part of Speech) Tag,

MySQL Select Query - Get only first 10 characters of a value

SELECT SUBSTRING(subject, 1, 10) FROM tbl

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

If you are not using "-XX:HeapDumpPath" option then in case of JBoss EAP/As by default the heap dump file will be generated in "JBOSS_HOME/bin" directory.

How to check if a service is running on Android?

Below is an elegant hack that covers all the Ifs. This is for local services only.

    public final class AService extends Service {

        private static AService mInstance = null;

        public static boolean isServiceCreated() {
            try {
                // If instance was not cleared but the service was destroyed an Exception will be thrown
                return mInstance != null && mInstance.ping();
            } catch (NullPointerException e) {
                // destroyed/not-started
                return false;
            }
        }

        /**
         * Simply returns true. If the service is still active, this method will be accessible.
         * @return
         */
        private boolean ping() {
            return true;
        }

        @Override
        public void onCreate() {
            mInstance = this;
        }

        @Override
        public void onDestroy() {
            mInstance = null;
        }
    }

And then later on:

    if(AService.isServiceCreated()){
        ...
    }else{
        startService(...);
    }

How to auto-remove trailing whitespace in Eclipse?

It is impossible to do it in Eclipse in generic way right now, but it can be changed given with basic Java knowledge and some free time to add basic support for this https://bugs.eclipse.org/bugs/show_bug.cgi?id=180349

The dependent issue: https://bugs.eclipse.org/bugs/show_bug.cgi?id=311173

Decoding JSON String in Java

Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.

To add the jar file to your project in Eclipse, do the following:

  1. Right click on your project, click Build Path > Configure Build Path
  2. Goto Libraries tab > Add External JARs
  3. Locate the JAR file and add

how to get a list of dates between two dates in java

You can also look at the Date.getTime() API. That gives a long to which you can add your increment. Then create a new Date.

List<Date> dates = new ArrayList<Date>();
long interval = 1000 * 60 * 60; // 1 hour in millis
long endtime = ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
  dates.add(new Date(curTime));
  curTime += interval;
}

and maybe apache commons has something like this in DateUtils, or perhaps they have a CalendarUtils too :)

EDIT

including the start and enddate may not be possible if your interval is not perfect :)

Display label text with line breaks in c#

You can also use <br/> where you want to break the text.

SHA-1 fingerprint of keystore certificate

As of Sept 2020, if you want to get the SHA-1 fingerprint of keystore certificate of Release. Simply open up your Google Play Developer Console and open the App Signing tab.

enter image description here

What is the meaning of "POSIX"?

POSIX defines set of standards for an operating system or a program. The goal is to write new software that is compatible with UNIX-like systems.

For example a program runs on Linux is also can be compile and run on other UNIX-like systems like Solaris, HP-UX, and AIX etc..

The most popular examples are GNU Bash which is 100% POSIX compliance and gawk utility.

how to create dynamic two dimensional array in java?

simple you want to inialize a 2d array and assign a size of array then a example is

   public static void main(String args[])
   { 
    char arr[][];   //arr is 2d array name
    arr = new char[3][3]; 
    }


   //this is a way to inialize a 2d array in java....  

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

How to convert an object to a byte array in C#

I took Crystalonics' answer and turned them into extension methods. I hope someone else will find them useful:

public static byte[] SerializeToByteArray(this object obj)
{
    if (obj == null)
    {
        return null;
    }
    var bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

public static T Deserialize<T>(this byte[] byteArray) where T : class
{
    if (byteArray == null)
    {
        return null;
    }
    using (var memStream = new MemoryStream())
    {
        var binForm = new BinaryFormatter();
        memStream.Write(byteArray, 0, byteArray.Length);
        memStream.Seek(0, SeekOrigin.Begin);
        var obj = (T)binForm.Deserialize(memStream);
        return obj;
    }
}

Accessing the logged-in user in a template

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

{% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

ImportError: No module named site on Windows

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

Cannot open output file, permission denied

The problem is that you don't have the administrator rights to access it as running or compilation of something is being done in the basic C drive. To eliminate this problem, run the devcpp.exe as an administrator. You could also change the permission from properties and allowing access read write modify etc for the system and by the system.

uppercase first character in a variable with bash

foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"

Clear contents of cells in VBA using column reference

You need a With statement prior to this. Or make the .Cells into Cells

How can I clear the input text after clicking

$("input:text").focus(function(){$(this).val("")});

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

Here is how you can solve this using a single WHERE clause:

WHERE (@myParm = value1 AND MyColumn IS NULL)
OR  (@myParm = value2 AND MyColumn IS NOT NULL)
OR  (@myParm = value3)

A naïve usage of the CASE statement does not work, by this I mean the following:

SELECT Field1, Field2 FROM MyTable
WHERE CASE @myParam
    WHEN value1 THEN MyColumn IS NULL
    WHEN value2 THEN MyColumn IS NOT NULL
    WHEN value3 THEN TRUE
END

It is possible to solve this using a case statement, see onedaywhen's answer

jQuery first child of "this"

I've added jsperf test to see the speed difference for different approaches to get the first child (total 1000+ children)

given, notif = $('#foo')

jQuery ways:

  1. $(":first-child", notif) - 4,304 ops/sec - fastest
  2. notif.children(":first") - 653 ops/sec - 85% slower
  3. notif.children()[0] - 1,416 ops/sec - 67% slower

Native ways:

  1. JavaScript native' ele.firstChild - 4,934,323 ops/sec (all the above approaches are 100% slower compared to firstChild)
  2. Native DOM ele from jQery: notif[0].firstChild - 4,913,658 ops/sec

So, first 3 jQuery approaches are not recommended, at least for first-child (I doubt that would be the case with many other too). If you have a jQuery object and need to get the first-child, then get the native DOM element from the jQuery object, using array reference [0] (recommended) or .get(0) and use the ele.firstChild. This gives the same identical results as regular JavaScript usage.

all tests are done in Chrome Canary build v15.0.854.0

Spark: subtract two DataFrames

In pyspark DOCS it would be subtract

df1.subtract(df2)

Can CSS force a line break after each word in an element?

Try using white-space: pre-line;. It creates a line-break wherever a line-break appears in the code, but ignores the extra whitespace (tabs and spaces etc.).

First, write your words on separate lines in your code:

<div>Short
Word</div>

Then apply the style to the element containing the words.

div { white-space: pre-line; }

Be careful though, every line break in the code inside the element will create a line break. So writing the following will result in an extra line break before the first word and after the last word:

<div>
    Short
    Word
</div>

There's a great article on CSS Tricks explaining the other white-space attributes.

array_push() with key value pair

Array['key'] = value;

$data['cat'] = 'wagon';

This is what you need. No need to use array_push() function for this. Some time the problem is very simple and we think in complex way :) .

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

C default arguments

I improved Jens Gustedt’s answer so that:

  1. inline functions aren’t employed
  2. defaults are computed during preprocessing
  3. modular reuseable macros
  4. possible to set compiler error that meaningfully matches the case of insufficient arguments for the allowed defaults
  5. the defaults aren’t required to form the tail of the parameter list if the argument types will remain unambiguous
  6. interopts with C11 _Generic
  7. vary the function name by the number of arguments!

variadic.h:

#ifndef VARIADIC

#define _NARG2(_0, _1, _2, ...) _2
#define NUMARG2(...) _NARG2(__VA_ARGS__, 2, 1, 0)
#define _NARG3(_0, _1, _2, _3, ...) _3
#define NUMARG3(...) _NARG3(__VA_ARGS__, 3, 2, 1, 0)
#define _NARG4(_0, _1, _2, _3, _4, ...) _4
#define NUMARG4(...) _NARG4(__VA_ARGS__, 4, 3, 2, 1, 0)
#define _NARG5(_0, _1, _2, _3, _4, _5, ...) _5
#define NUMARG5(...) _NARG5(__VA_ARGS__, 5, 4, 3, 2, 1, 0)
#define _NARG6(_0, _1, _2, _3, _4, _5, _6, ...) _6
#define NUMARG6(...) _NARG6(__VA_ARGS__, 6, 5, 4, 3, 2, 1, 0)
#define _NARG7(_0, _1, _2, _3, _4, _5, _6, _7, ...) _7
#define NUMARG7(...) _NARG7(__VA_ARGS__, 7, 6, 5, 4, 3, 2, 1, 0)
#define _NARG8(_0, _1, _2, _3, _4, _5, _6, _7, _8, ...) _8
#define NUMARG8(...) _NARG8(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define _NARG9(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) _9
#define NUMARG9(...) _NARG9(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define __VARIADIC(name, num_args, ...) name ## _ ## num_args (__VA_ARGS__)
#define _VARIADIC(name, num_args, ...) name (__VARIADIC(name, num_args, __VA_ARGS__))
#define VARIADIC(name, num_args, ...) _VARIADIC(name, num_args, __VA_ARGS__)
#define VARIADIC2(name, num_args, ...) __VARIADIC(name, num_args, __VA_ARGS__)

// Vary function name by number of arguments supplied
#define VARIADIC_NAME(name, num_args) name ## _ ## num_args ## _name ()
#define NVARIADIC(name, num_args, ...) _VARIADIC(VARIADIC_NAME(name, num_args), num_args, __VA_ARGS__)

#endif

Simplified usage scenario:

const uint32*
uint32_frombytes(uint32* out, const uint8* in, size_t bytes);

/*
The output buffer defaults to NULL if not provided.
*/

#include "variadic.h"

#define uint32_frombytes_2(   b, c) NULL, b, c
#define uint32_frombytes_3(a, b, c)    a, b, c
#define uint32_frombytes(...) VARIADIC(uint32_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

And with _Generic:

const uint8*
uint16_tobytes(const uint16* in, uint8* out, size_t bytes);

const uint16*
uint16_frombytes(uint16* out, const uint8* in, size_t bytes);

const uint8*
uint32_tobytes(const uint32* in, uint8* out, size_t bytes);

const uint32*
uint32_frombytes(uint32* out, const uint8* in, size_t bytes);

/*
The output buffer defaults to NULL if not provided.
Generic function name supported on the non-uint8 type, except where said type
is unavailable because the argument for output buffer was not provided.
*/

#include "variadic.h"

#define   uint16_tobytes_2(a,    c) a, NULL, c
#define   uint16_tobytes_3(a, b, c) a,    b, c
#define   uint16_tobytes(...) VARIADIC(  uint16_tobytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define uint16_frombytes_2(   b, c) NULL, b, c
#define uint16_frombytes_3(a, b, c)    a, b, c
#define uint16_frombytes(...) VARIADIC(uint16_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define   uint32_tobytes_2(a,    c) a, NULL, c
#define   uint32_tobytes_3(a, b, c) a,    b, c
#define   uint32_tobytes(...) VARIADIC(  uint32_tobytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define uint32_frombytes_2(   b, c) NULL, b, c
#define uint32_frombytes_3(a, b, c)    a, b, c
#define uint32_frombytes(...) VARIADIC(uint32_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define   tobytes(a, ...) _Generic((a),                                                                                                 \
                                   const uint16*: uint16_tobytes,                                                                       \
                                   const uint32*: uint32_tobytes)  (VARIADIC2(  uint32_tobytes, NUMARG3(a, __VA_ARGS__), a, __VA_ARGS__))

#define frombytes(a, ...) _Generic((a),                                                                                                 \
                                         uint16*: uint16_frombytes,                                                                     \
                                         uint32*: uint32_frombytes)(VARIADIC2(uint32_frombytes, NUMARG3(a, __VA_ARGS__), a, __VA_ARGS__))

And with variadic function name selection, which can't be combined with _Generic:

// winternitz() with 5 arguments is replaced with merkle_lamport() on those 5 arguments.

#define   merkle_lamport_5(a, b, c, d, e) a, b, c, d, e
#define   winternitz_7(a, b, c, d, e, f, g) a, b, c, d, e, f, g
#define   winternitz_5_name() merkle_lamport
#define   winternitz_7_name() winternitz
#define   winternitz(...) NVARIADIC(winternitz, NUMARG7(__VA_ARGS__), __VA_ARGS__)

Globally catch exceptions in a WPF application?

Use the Application.DispatcherUnhandledException Event. See this question for a summary (see Drew Noakes' answer).

Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.

tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement"

I think this message is not about avoiding to use switch. Instead it wants you to check for hasOwnProperty. The background can be read here: https://stackoverflow.com/a/16735184/1374488

HTTP error 403 in Python 3 Web Scraping

Since the page works in browser and not when calling within python program, it seems that the web app that serves that url recognizes that you request the content not by the browser.

Demonstration:

curl --dump-header r.txt http://www.cmegroup.com/trading/products/#sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1

...
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>
You don't have permission to access ...
</HTML>

and the content in r.txt has status line:

HTTP/1.1 403 Forbidden

Try posting header 'User-Agent' which fakes web client.

NOTE: The page contains Ajax call that creates the table you probably want to parse. You'll need to check the javascript logic of the page or simply using browser debugger (like Firebug / Net tab) to see which url you need to call to get the table's content.

Inheriting constructors

Constructors are not inherited. They are called implicitly or explicitly by the child constructor.

The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.

class A
{
public: 
    explicit A(int x) {}
};

class B: public A
{
public:
    explicit B(int x) : A(x) { }
};

UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.

List of standard lengths for database fields

These might be useful to someone;

youtube max channel length = 20
facebook max name length   = 50
twitter max handle length  = 15
email max length           = 255 

http://www.interoadvisory.com/2015/08/6-areas-inside-of-linkedin-with-character-limits/

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Here is dirty way:

  1. Log into a linux server using "ssh -X user@host"
  2. open rxvt-unicode or other X terminal.
  3. open tmux or screen
  4. Log back into your local computer from the server
  5. start your favourite shell such as msys or cygwin.

Reading from a text file and storing in a String

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

How can you search Google Programmatically Java API

Just an alternative. Searching google and parsing the results can also be done in a generic way using any HTML Parser such as Jsoup in Java. Following is the link to the mentioned example.

Update: Link no longer works. Please look for any other example. https://www.codeforeach.com/java/example-how-to-search-google-using-java

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

Detect all changes to a <input type="text"> (immediately) using JQuery

you can see this example and choose which are the events that interest you:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<title>evetns</title>
</head>
<body>
<form>
    <input class="controlevents" id="i1" type="text" /><br />
    <input class="controlevents" id="i2" type="text" /><br />
    <input class="controlevents" id="i3" type="text" /><br />
    <input class="controlevents" id="i4" type="text" /><br />
    <input class="controlevents" id="i5" type="text" /><br />
</form>
<div id="datatext"></div>
</body>
</html>
<script>
$(function(){

function testingevent(ev){
    if (ev.currentTarget.tagName=="INPUT")
        $("#datatext").append("<div>id : " + ev.currentTarget.id + ", tag: " + ev.currentTarget.tagName + ", type: "+ ev.type +"</div>");
}   

    var eventlist = ["resizeend","rowenter","dragleave","beforepaste","dragover","beforecopy","page","beforeactivate","beforeeditfocus","controlselect","blur",
                    "beforedeactivate","keydown","dragstart","scroll","propertychange","dragenter","rowsinserted","mouseup","contextmenu","beforeupdate",
                    "readystatechange","mouseenter","resize","copy","selectstart","move","dragend","rowexit","activate","focus","focusin","mouseover","cut",
                    "mousemove","focusout","filterchange","drop","blclick","rowsdelete","keypress","losecapture","deactivate","datasetchanged","dataavailable",
                    "afterupdate","mousewheel","keyup","movestart","mouseout","moveend","cellchange","layoutcomplete","help","errorupdate","mousedown","paste",
                    "mouseleave","click","drag","resizestart","datasetcomplete","beforecut","change","error","abort","load","select"];

    var inputs = $(".controlevents");

    $.each(eventlist, function(i, el){
        inputs.bind(el, testingevent);
    });

});
</script>

Select value from list of tuples where condition

One solution to this would be a list comprehension, with pattern matching inside your tuple:

>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]

Another way would be using map and filter:

>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

This one helped me. Try creating a new folder, if your MongoDB is installed in C:\Program Files the folder should be called db and in a folder data. C:\data\db

When you start the mongod there should be a log where the db 'isnt found'.

No Network Security Config specified, using platform default - Android Log

The message you're getting isn't an error; it's just letting you know that you're not using a Network Security Configuration. If you want to add one, take a look at this page on the Android Developers website: https://developer.android.com/training/articles/security-config.html.

How to display hexadecimal numbers in C?

i use it like this:

printf("my number is 0x%02X\n",number);
// output: my number is 0x4A

Just change number "2" to any number of chars You want to print ;)

Check if a Class Object is subclass of another Class Object in Java

Another option is instanceof:

Object o =...
if (o instanceof Number) {
  double d = ((Number)o).doubleValue(); //this cast is safe
}

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

If you are using Sql Management Studio, just start it as Administrator.

Right click->Run as Administrator

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

How to run python script with elevated privilege on windows

in comments to the answer you took the code from someone says ShellExecuteEx doesn't post its STDOUT back to the originating shell. so you will not see "I am root now", even though the code is probably working fine.

instead of printing something, try writing to a file:

import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    sys.exit(0)
with open("somefilename.txt", "w") as out:
    print >> out, "i am root"

and then look in the file.

How do I check if a string is valid JSON in Python?

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

IF statement: how to leave cell blank if condition is false ("" does not work)

I wanted to add that there is another possibility - to use the function na().

e.g. =if(a2 = 5,"good",na());

This will fill the cell with #N/A and if you chart the column, the data won't be graphed. I know it isn't "blank" as such, but it's another possibility if you have blank strings in your data and "" is a valid option.

Also, count(a:a) will not count cells which have been set to n/a by doing this.

Webview load html from assets directory

Download source code from here (Open html file from assets android)

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:background="#FFFFFF"
 android:layout_height="match_parent">

<WebView
 android:layout_width="match_parent"
 android:id="@+id/webview"
 android:layout_height="match_parent"
 android:layout_margin="10dp"></WebView>
</RelativeLayout>

MainActivity.java

package com.deepshikha.htmlfromassets;
 import android.app.ProgressDialog;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

WebView webview;
 ProgressDialog progressDialog;

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

private void init(){
 webview = (WebView)findViewById(R.id.webview);
 webview.loadUrl("file:///android_asset/download.html");
 webview.requestFocus();

progressDialog = new ProgressDialog(MainActivity.this);
 progressDialog.setMessage("Loading");
 progressDialog.setCancelable(false);
 progressDialog.show();

webview.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
 try {
 progressDialog.dismiss();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 }

A generic error occurred in GDI+, JPEG Image to MemoryStream

Error occurring because of Permission. make sure folder have ALL THE PERMISSION.

public Image Base64ToImage(string base64String)
    {
        // Convert Base64 String to byte[]
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0,
          imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true);
        return image;
    }

 img.Save("YOUR PATH TO SAVE IMAGE")

Get the value of bootstrap Datetimepicker in JavaScript

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

Add class to <html> with Javascript?

document.documentElement.classList.add('myCssClass');

classList is supported since ie10: https://caniuse.com/#search=classlist

Why is my Git Submodule HEAD detached from master?

I am also still figuring out the internals of git, and have figured out this so far:

  1. HEAD is a file in your .git/ directory that normally looks something like this:
% cat .git/HEAD
ref: refs/heads/master
  1. refs/heads/master is itself a file that normally has the hash value of the latest commit:
% cat .git/refs/heads/master 
cbf01a8e629e8d884888f19ac203fa037acd901f
  1. If you git checkout a remote branch that is ahead of your master, this may cause your HEAD file to be updated to contain the hash of the latest commit in the remote master:
% cat .git/HEAD
8e2c815f83231f85f067f19ed49723fd1dc023b7

This is called a detached HEAD. The remote master is ahead of your local master. When you do git submodule --remote myrepo to get the latest commit of your submodule, it will by default do a checkout, which will update HEAD. Since your current branch master is behind, HEAD becomes 'detached' from your current branch, so to speak.

How to set Highcharts chart maximum yAxis value

Alternatively one can use the setExtremes method also,

yAxis.setExtremes(0, 100);

Or if only one value is needed to be set, just leave other as null

yAxis.setExtremes(null, 100);

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get the actual access_token, you can also do pro grammatically via the following PHP code:

 require 'facebook.php';

 $facebook = new Facebook(array(
   'appId'  => 'YOUR_APP_ID',
   'secret' => 'YOUR_APP_SECRET',
 ));

 // Get User ID
 $user = $facebook->getUser();

 if ($user) {
   try {
     $user_profile = $facebook->api('/me');
     $access_token = $facebook->getAccessToken();
   } catch (FacebookApiException $e) {
     error_log($e);
     $user = null;
   }
 }

Language Books/Tutorials for popular languages

C

K.N. King has a list of recommended C books in his personal page:

  • The C Puzzle Book (Revised Edition)
  • C: A Reference Manual, Fifth Edition
  • C Unleashed
  • C Traps and Pitfalls
  • Expert C Programming

CSS/Javascript to force html table row on a single line

I wonder if it might be worth using PHP (or another server-side scripting language) or Javascript to truncate the strings to the right length (although calculating the right length is tricky, unless you use a fixed-width font)?

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

The problem is the ssl certificate on server side. Either something is interfering or the certificate doesn't match the service. For instance when a site has a ssl cert for www.mydomain.com while the service you use runs on myservice.mydomain.com. That is a different machine.

jQuery - add additional parameters on submit (NOT ajax)

You can even use this one. worked well for me

$("#registerform").attr("action", "register.php?btnsubmit=Save") 
$('#registerform').submit();

this will submit btnsubmit =Save as GET value to register.php form.

Use dynamic variable names in JavaScript

This will do exactly what you done in php:

var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1

Android: adb: Permission Denied

data partition not accessible for non root user, if you want to access it you must root your phone.

adb root not work for all product and depend in phone build type.

in new version on android studio you can explore /data/data path for debuggable apps.

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

How to convert View Model into JSON object in ASP.NET MVC?

In mvc3 with razor @Html.Raw(Json.Encode(object)) seems to do the trick.

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

git pull error "The requested URL returned error: 503 while accessing"

here you can see the latest updated status form their website

bitbucket site status

if Git via HTTPS status is Major Outage, you will not be able to pull/push, let this status to get green

HTTP Error 503 - Service unavailable

Histogram Matplotlib

I know this does not answer your question, but I always end up on this page, when I search for the matplotlib solution to histograms, because the simple histogram_demo was removed from the matplotlib example gallery page.

Here is a solution, which doesn't require numpy to be imported. I only import numpy to generate the data x to be plotted. It relies on the function hist instead of the function bar as in the answer by @unutbu.

import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

enter image description here

Also check out the matplotlib gallery and the matplotlib examples.

How to iterate over the keys and values with ng-repeat in AngularJS?

    Use below code it is working to display your key and value here is key start with 1:
         <tr ng-repeat="(key,value) in alert_list" >
                   <td>{{key +1}}</td>
                   <td>{{value.title}}</td>
                 </tr>
Below is document link for it. 

https://docs.angularjs.org/api/ng/directive/ngRepeat

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

In my case the reason was since the remote repo artifact (non-central) had dependencies from the Maven Central in the .pom file, and the older version of mvn (older than 3.6.0) was used. So, it tried to check the Maven Central artifacts mentioned in the remote repo's .pom for the specific artifact I've added to my dependencies and faced the Maven Central http access issue behind the scenes (I believe the same as described there: Maven dependencies are failing with a 501 error - that is about using https access to Maven Central by default and prohibiting the http access).

Using more recent Maven (from 3.1 to 3.6.0) made it use https to check Maven Central repo dependencies mentioned in the .pom files of the remote repositories and I no longer face the issue.

openpyxl - adjust column width size

I had to change @User3759685 above answer to this when the openpxyl updated. I was getting an error. Well @phihag reported this in the comments as well

for column_cells in ws.columns:
    new_column_length = max(len(as_text(cell.value)) for cell in column_cells)
    new_column_letter = (openpyxl.utils.get_column_letter(column_cells[0].column))
    if new_column_length > 0:
        ws.column_dimensions[new_column_letter].width = new_column_length + 1

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

Email & Phone Validation in Swift

Swift 3.0 to 5.0 Updated Solution:

//MARK:- Validation Extension -

extension String {

    //To check text field or String is blank or not
    var isBlank: Bool {
        get {
            let trimmed = trimmingCharacters(in: CharacterSet.whitespaces)
            return trimmed.isEmpty
        }
    }

    //Validate Email

    var isEmail: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: .caseInsensitive)
            return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
        } catch {
            return false
        }
    }

    var isAlphanumeric: Bool {
        return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
    }

    //validate Password
    var isValidPassword: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "^[a-zA-Z_0-9\\-_,;.:#+*?=!§$%&/()@]+$", options: .caseInsensitive)
            if(regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil){

                if(self.characters.count>=6 && self.count<=20){
                    return true
                }else{
                    return false
                }
            }else{
                return false
            }
        } catch {
            return false
        }
    }
}

use of Email Validation:

if(txtEmail.isEmail){
}

Swift 2.0 Solution

Paste these line anywhere in code.(or in your Constant file)

extension String {

    //To check text field or String is blank or not
    var isBlank: Bool {
        get {
            let trimmed = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
            return trimmed.isEmpty
        }
    }

    //Validate Email
    var isEmail: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: .CaseInsensitive)
            return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
        } catch {
            return false
        }
    }

    //validate PhoneNumber
    var isPhoneNumber: Bool {

        let charcter  = NSCharacterSet(charactersInString: "+0123456789").invertedSet
        var filtered:NSString!
        let inputString:NSArray = self.componentsSeparatedByCharactersInSet(charcter)
        filtered = inputString.componentsJoinedByString("")
        return  self == filtered

    }
}

Tower of Hanoi: Recursive Algorithm

After reading all these explanations I thought I'd weigh in with the method my professor used to explain the Towers of Hanoi recursive solution. Here is the algorithm again with n representing the number of rings, and A, B, C representing the pegs. The first parameter of the function is the number of rings, second parameter represents the source peg, the third is the destination peg, and fourth is the spare peg.

procedure Hanoi(n, A, B, C);
  if n == 1
    move ring n from peg A to peg B
  else
    Hanoi(n-1, A, C, B);
    move ring n-1 from A to C
    Hanoi(n-1, C, B, A);
end;

I was taught in graduate school to never to be ashamed to think small. So, let's look at this algorithm for n = 5. The question to ask yourself first is if I want to move the 5th ring from A to B, where are the other 4 rings? If the 5th ring occupies peg A and we want to move it to peg B, then the other 4 rings can only be on peg C. In the algorithm above the function Hanoi (n-1, A, C, B) is trying to move all those 4 other rings on to peg C, so ring 5 will be able to move from A to B. Following this algorithm we look at n = 4. If ring 4 will be moved from A to C, where are rings 3 and smaller? They can only be on peg B. Next, for n = 3, if ring 3 will be moved from A to B, where are rings 2 and 1? On peg C of course. If you continue to follow this pattern you can visualize what the recursive algorithm is doing. This approach differs from the novice's approach in that it looks at the last disk first and the first disk last.

Single Page Application: advantages and disadvantages

Disadvantages

1. Client must enable javascript. Yes, this is a clear disadvantage of SPA. In my case I know that I can expect my users to have JavaScript enabled. If you can't then you can't do a SPA, period. That's like trying to deploy a .NET app to a machine without the .NET Framework installed.

2. Only one entry point to the site. I solve this problem using SammyJS. 2-3 days of work to get your routing properly set up, and people will be able to create deep-link bookmarks into your app that work correctly. Your server will only need to expose one endpoint - the "give me the HTML + CSS + JS for this app" endpoint (think of it as a download/update location for a precompiled application) - and the client-side JavaScript you write will handle the actual entry into the application.

3. Security. This issue is not unique to SPAs, you have to deal with security in exactly the same way when you have an "old-school" client-server app (the HATEOAS model of using Hypertext to link between pages). It's just that the user is making the requests rather than your JavaScript, and that the results are in HTML rather than JSON or some data format. In a non-SPA app you have to secure the individual pages on the server, whereas in a SPA app you have to secure the data endpoints. (And, if you don't want your client to have access to all the code, then you have to split apart the downloadable JavaScript into separate areas as well. I simply tie that into my SammyJS-based routing system so the browser only requests things that the client knows it should have access to, based on an initial load of the user's roles, and then that becomes a non-issue.)

Advantages

  1. A major architectural advantage of a SPA (that rarely gets mentioned) in many cases is the huge reduction in the "chattiness" of your app. If you design it properly to handle most processing on the client (the whole point, after all), then the number of requests to the server (read "possibilities for 503 errors that wreck your user experience") is dramatically reduced. In fact, a SPA makes it possible to do entirely offline processing, which is huge in some situations.

  2. Performance is certainly better with client-side rendering if you do it right, but this is not the most compelling reason to build a SPA. (Network speeds are improving, after all.) Don't make the case for SPA on this basis alone.

  3. Flexibility in your UI design is perhaps the other major advantage that I have found. Once I defined my API (with an SDK in JavaScript), I was able to completely rewrite my front-end with zero impact on the server aside from some static resource files. Try doing that with a traditional MVC app! :) (This becomes valuable when you have live deployments and version consistency of your API to worry about.)

So, bottom line: If you need offline processing (or at least want your clients to be able to survive occasional server outages) - dramatically reducing your own hardware costs - and you can assume JavaScript & modern browsers, then you need a SPA. In other cases it's more of a tradeoff.

How to determine the IP address of a Solaris system

hostname and uname will give you the name of the host. Then use nslookup to translate that to an IP address.

How to cd into a directory with space in the name?

SOLUTION:

cd "Documents and Photos"

problem solved.

The reason I'm submitting this answer is you'll find that StackOverflow is being used by every day users (not just web devs, programmers or power users) and this was the number one result for a simple Windows user question on Google.

People are becoming more tech-savvy, but aren't necessarily familiar with command line in the cases above.

How to determine MIME type of file in android?

// This will return the mimeType. 
// for eg. xyz.png it will return image/png. 
// here uri is the file that we were picked using intent from ext/internal storage.
private String getMimeType(Uri uri) {
   // This class provides applications access to the content model.  
   ContentResolver contentResolver = getContentResolver();

   // getType(Uri url)-Return the MIME type of the given content URL. 
   return contentResolver.getType(uri);
}

INNER JOIN vs LEFT JOIN performance in SQL Server

Your performance problems are more likely to be because of the number of joins you are doing and whether the columns you are joining on have indexes or not.

Worst case you could easily be doing 9 whole table scans for each join.

CreateProcess error=2, The system cannot find the file specified

I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

I got an error. But if I ran

ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

everything was OK.

Retrieve a Fragment from a ViewPager

Add next methods to your FragmentPagerAdapter:

public Fragment getActiveFragment(ViewPager container, int position) {
String name = makeFragmentName(container.getId(), position);
return  mFragmentManager.findFragmentByTag(name);
}

private static String makeFragmentName(int viewId, int index) {
    return "android:switcher:" + viewId + ":" + index;
}

getActiveFragment(0) has to work.

Here is the solution implemented into ViewPager https://gist.github.com/jacek-marchwicki/d6320ba9a910c514424d. If something fail you will see good crash log.

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

How to reset Android Studio

On a Mac

Delete these using the terminal (usage: rm -rf folderpath):

~/Library/Preferences/AndroidStudioBeta
~/Library/Application Support/AndroidStudioBeta
~/Library/Caches/AndroidStudioBeta
~/Library/Logs/AndroidStudioBeta

Regarding C++ Include another class

The thing with compiling two .cpp files at the same time, it doesnt't mean they "know" about eachother. You will have to create a file, the "tells" your File1.cpp, there actually are functions and classes like ClassTwo. This file is called header-file and often doesn't include any executable code. (There are exception, e.g. for inline functions, but forget them at first) They serve a declarative need, just for telling, which functions are available.

When you have your File2.cpp and include it into your File1.cpp, you see a small problem: There is the same code twice: One in the File1.cpp and one in it's origin, File2.cpp.

Therefore you should create a header file, like File1.hpp or File1.h (other names are possible, but this is simply standard). It works like the following:

//File1.cpp

void SomeFunc(char c) //Definition aka Implementation
{
//do some stuff
}

//File1.hpp

void SomeFunc(char c); //Declaration aka Prototype

And for a matter of clean code you might add the following to the top of File1.cpp:

#include "File1.hpp"

And the following, surrounding File1.hpp's code:

#ifndef FILE1.HPP_INCLUDED
#define FILE1.HPP_INCLUDED
//
//All your declarative code
//
#endif

This makes your header-file cleaner, regarding to duplicate code.

Git: How to check if a local repo is up to date?

This is impossible without using git fetch or git pull. How can you know whether or not the repository is "up-to-date" without going to the remote repository to see what "up-to-date" even means?

How to sum digits of an integer in java?

public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum); 
}

Output

6

Combination of async function + await + setTimeout

setTimeout is not an async function, so you can't use it with ES7 async-await. But you could implement your sleep function using ES6 Promise:

function sleep (fn, par) {
  return new Promise((resolve) => {
    // wait 3s before calling fn(par)
    setTimeout(() => resolve(fn(par)), 3000)
  })
}

Then you'll be able to use this new sleep function with ES7 async-await:

var fileList = await sleep(listFiles, nextPageToken)

Please, note that I'm only answering your question about combining ES7 async/await with setTimeout, though it may not help solve your problem with sending too many requests per second.


Update: Modern node.js versions has a buid-in async timeout implementation, accessible via util.promisify helper:

const {promisify} = require('util');
const setTimeoutAsync = promisify(setTimeout);

Maven in Eclipse: step by step installation

I have also come across the same issue and figuredout the issue here is the solution.

Lot of people assumes Eclipse and maven intergration is tough but its very eassy.

1) download the maven and unzip it in to your favorite directory.

Ex : C:\satyam\DEV_TOOLS\apache-maven-3.1.1

2) Set the environment variable for Maven(Hope every one knows where to go to set this)

In the system variable: Variable_name = M2_HOME Variable_Value =C:\satyam\DEV_TOOLS\apache-maven-3.1.1

Next in the same System Variable you will find the variable name called Path: just edit the path variable and add M2_HOME details like with the existing values.

%M2_HOME%/bin;

so in the second step now you are done setting the Maven stuff to your system.you need to cross check it whether your setting is correct or not, go to command prompt and type mvn--version it should disply the path of your Maven

3) Open the eclipse and go to Install new software and type M2E Plugin install and restart the Eclipse

with the above 3 steps you are done with Maven and Maven Plugin with eclipse

4) Maven is used .m2 folder to download all the jars, it will find in Ex: C:\Users\tempsakat.m2

under this folder one settings.xml file and one repository folder will be there

5) go to Windwo - preferences of your Eclipse and type Maven then select UserSettings from left menu then give the path of the settings.xml here .

now you are done...

Why is `input` in Python 3 throwing NameError: name... is not defined

You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print statement would throw up a SyntaxError before it ever prompted you for input.

The result is that you're using Python 2's input, which tries to eval your input (presumably sdas), finds that it's invalid Python, and dies.

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

First copy bson.js code from browser_build folder

second create new file bson.js and paste code

third save the new file near to in index.js.

how to delete default values in text field using selenium?

You can use the code below. It selects the pre-existing value in the field and overwrites it with the new value.

driver.findElement(By.xpath("*enter your xpath here*")).sendKeys(Keys.chord(Keys.CONTROL, "a"),*enter the new value here*);

Python: how to capture image from webcam on click using OpenCV

This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.

import cv2
import sys
import logging as log
import datetime as dt
from time import sleep

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)

video_capture = cv2.VideoCapture(0)
anterior = 0

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass

    # Capture frame-by-frame
    ret, frame = video_capture.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30)
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    if anterior != len(faces):
        anterior = len(faces)
        log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))


    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('s'): 

        check, frame = video_capture.read()
        cv2.imshow("Capturing", frame)
        cv2.imwrite(filename='saved_img.jpg', img=frame)
        video_capture.release()
        img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
        img_new = cv2.imshow("Captured Image", img_new)
        cv2.waitKey(1650)
        print("Image Saved")
        print("Program End")
        cv2.destroyAllWindows()

        break
    elif cv2.waitKey(1) & 0xFF == ord('q'):
        print("Turning off camera.")
        video_capture.release()
        print("Camera off.")
        print("Program ended.")
        cv2.destroyAllWindows()
        break

    # Display the resulting frame
    cv2.imshow('Video', frame)

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()

output

enter image description here

Also, You can check out my GitHub code

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

? is called Ternary (conditional) operator : example

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

Pythonic way of checking if a condition holds for any element of a list

Python has a built in any() function for exactly this purpose.

Trigger an action after selection select2

//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

Configure apache to listen on port other than 80

For FC22 server

cd /etc/httpd/conf edit httpd.conf [enter]

Change: Listen 80 to: Listen whatevernumber

Save the file

systemctl restart httpd.service [enter] if required, open whatevernumber in your router / firewall

Difference between Java SE/EE/ME?

Yes, Java SE is where to start. All the tasks you mention can be handled with it.

Java ME is the Mobile Edition, and EE is Enterprise Edition; these are specialized / extended versions of Standard Edition.

How to print a list with integers without the brackets, commas and no quotes?

Using .format from Python 2.6 and higher:

>>> print '{}{}{}{}'.format(*[7,7,7,7])
7777
>>> data = [7, 7, 7, 7] * 3
>>> print ('{}'*len(data)).format(*data)
777777777777777777777777

For Python 3:

>>> print(('{}'*len(data)).format(*data))
777777777777777777777777

Correct way to convert size in bytes to KB, MB, GB in JavaScript

From this: (source)

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

Note : This is original code, Please use fixed version below. Aliceljm does not active her copied code anymore


Now, Fixed version unminified, and ES6'ed: (by community)

function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

Now, Fixed version : (by Stackoverflow's community, + Minified by JSCompress)

function formatBytes(a,b=2){if(0===a)return"0 Bytes";const c=0>b?0:b,d=Math.floor(Math.log(a)/Math.log(1024));return parseFloat((a/Math.pow(1024,d)).toFixed(c))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}

Usage :

// formatBytes(bytes,decimals)

formatBytes(1024);       // 1 KB
formatBytes('1024');     // 1 KB
formatBytes(1234);       // 1.21 KB
formatBytes(1234, 3);    // 1.205 KB

Demo / source :

_x000D_
_x000D_
function formatBytes(bytes, decimals = 2) {_x000D_
    if (bytes === 0) return '0 Bytes';_x000D_
_x000D_
    const k = 1024;_x000D_
    const dm = decimals < 0 ? 0 : decimals;_x000D_
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];_x000D_
_x000D_
    const i = Math.floor(Math.log(bytes) / Math.log(k));_x000D_
_x000D_
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];_x000D_
}_x000D_
_x000D_
// ** Demo code **_x000D_
var p = document.querySelector('p'),_x000D_
    input = document.querySelector('input');_x000D_
    _x000D_
function setText(v){_x000D_
    p.innerHTML = formatBytes(v);_x000D_
}_x000D_
// bind 'input' event_x000D_
input.addEventListener('input', function(){ _x000D_
    setText( this.value )_x000D_
})_x000D_
// set initial text_x000D_
setText(input.value);
_x000D_
<input type="text" value="1000">_x000D_
<p></p>
_x000D_
_x000D_
_x000D_

PS : Change k = 1000 or sizes = ["..."] as you want (bits or bytes)

How to add a set path only for that batch file executing?

That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:

setx ENV_VAR_NAME "DESIRED_PATH" /m

This will change it permanently and yes you can overwrite it by another batch script.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

It looks like mysql service is either not working or stopped. you can start it by using below command (in Ubuntu):

service mysql start

It should work! If you are using any other operating system than Ubuntu then use appropriate way to start mysql

Case-insensitive search in Rails model

Upper and lower case letters differ only by a single bit. The most efficient way to search them is to ignore this bit, not to convert lower or upper, etc. See keywords COLLATION for MSSQL, see NLS_SORT=BINARY_CI if using Oracle, etc.

Attach IntelliJ IDEA debugger to a running Java process

It's possible, but you have to add some JVM flags when you start your application.

You have to add remote debug configuration: Edit configuration -> Remote.

Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y)

ERROR Android emulator gets killed

This worked for me:

Tools -> SDK Manager -> SDK Tools (tab) -> Deselect 'Android Emulator' -> OK

Now, when you try to run your app, or launch device from AVD Manager, it will give the 'Install Emulator' error -> Click Ok. This will automatically download the correct version.

error code 1292 incorrect date value mysql

I was having the same issue in Workbench plus insert query from C# application. In my case using ISO format solve the issue

string value = date.ToString("yyyy-MM-dd HH:mm:ss");

How to navigate through textfields (Next / Done Buttons)

Here is an implementation of tabbing using a category on UIControl. This solution has all of the advantages of the methods from Michael and Anth0, but works for all UIControls, not just UITextFields. It also works seamlessly with Interface Builder and storyboards.

Source and sample app: GitHub repository for UIControlsWithTabbing

Usage:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField transferFirstResponderToNextControl];
    return NO;
}

Assigning nextControl in Interface Builder

Header:

//
// UIControl+NextControl.h
// UIControlsWithTabbing
//

#import <UIKit/UIKit.h>

@interface UIControl (NextControl)

@property (nonatomic, weak) IBOutlet UIControl *nextControl;

- (BOOL)transferFirstResponderToNextControl;

@end

Implementation:

#import "UIControl+NextControl.h"
#import <objc/runtime.h>

static char defaultHashKey;

@implementation UIControl (NextControl)

- (UIControl *)nextControl
{
    return objc_getAssociatedObject(self, &defaultHashKey);
}

- (void)setNextControl:(UIControl *)nextControl
{
    objc_setAssociatedObject(self, &defaultHashKey, nextControl, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)transferFirstResponderToNextControl
{
    if (self.nextControl)
    {
        [self.nextControl becomeFirstResponder];

        return YES;
    }

    [self resignFirstResponder];

    return NO;
}

@end

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

What does the red exclamation point icon in Eclipse mean?

Make sure you don't have any undefined classpath variables (like M2_REPO).

ImportError: No module named 'Tkinter'

--------- WORKED ON PYTHON 2.7------------

Install all below packages

sudo apt-get install git
sudo apt-get install python-tk
sudo apt-get install python-pip
sudo apt install picolisp
sudo -H pip2 install --upgrade pip
sudo pip install -I pillow
sudo apt-get install python-imaging-tk
sudo apt-get install python-tk

Using Mockito with multiple calls to the same method with the same arguments

BDD style:

import static org.mockito.BDDMockito.given;
        ...

        given(yourMock.yourMethod()).willReturn(1, 2, 3);

Classic style:

import static org.mockito.Mockito.when;
        ...

        when(yourMock.yourMethod()).thenReturn(1, 2, 3);

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

Makefiles with source files in different directories

Recursive Use of Make

all:
    +$(MAKE) -C part1
    +$(MAKE) -C part2
    +$(MAKE) -C part3

This allows for make to split into jobs and use multiple cores

Preloading images with JavaScript

You can move this code to index.html for preload images from any url

<link rel="preload" href="https://via.placeholder.com/160" as="image">

How to send control+c from a bash script?

    pgrep -f process_name > any_file_name
    sed -i 's/^/kill /' any_file_name
    chmod 777 any_file_name
    ./any_file_name

for example 'pgrep -f firefox' will grep the PID of running 'firefox' and will save this PID to a file called 'any_file_name'. 'sed' command will add the 'kill' in the beginning of the PID number in 'any_file_name' file. Third line will make 'any_file_name' file executable. Now forth line will kill the PID available in the file 'any_file_name'. Writing the above four lines in a file and executing that file can do the control-C. Working absolutely fine for me.

How to disable spring security for particular url

<http pattern="/resources/**" security="none"/>

Or with Java configuration:

web.ignoring().antMatchers("/resources/**");

Instead of the old:

 <intercept-url pattern="/resources/**" filters="none"/>

for exp . disable security for a login page :

  <intercept-url pattern="/login*" filters="none" />

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

As an addition to Darin Dimitrov's answer:

If you only want this particular line to use a certain (different from standard) format, you can use in MVC5:

@Html.EditorFor(model => model.Property, new {htmlAttributes = new {@Value = @Model.Property.ToString("yyyy-MM-dd"), @class = "customclass" } })

jquery: $(window).scrollTop() but no $(window).scrollBottom()

I would say that a scrollBottom as a direct opposite of scrollTop should be:

var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

Here is a small ugly test that works for me:

// SCROLLTESTER START //
$('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>').insertAfter('body');

$(window).scroll(function () {
  var st = $(window).scrollTop();
  var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

  $('#st').replaceWith('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;">scrollTop: ' + st + '<br>scrollBottom: ' + scrollBottom + '</h1>');
});
// SCROLLTESTER END //

Sort objects in an array alphabetically on one property of the array

DEMO

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

console.log(objArray.sort(function(a, b) { return a.name > b.name}));

split string in two on given index and return both parts

ES6 1-liner

_x000D_
_x000D_
// :: splitAt = number => Array<any>|string => Array<Array<any>|string>_x000D_
const splitAt = index => x => [x.slice(0, index), x.slice(index)]_x000D_
_x000D_
console.log(_x000D_
  splitAt(1)('foo'), // ["f", "oo"]_x000D_
  splitAt(2)([1, 2, 3, 4]) // [[1, 2], [3, 4]]_x000D_
)_x000D_
  
_x000D_
_x000D_
_x000D_

Is it possible to create a temporary table in a View and drop it after select?

You can achieve what you are trying to do, using a Stored Procedure which returns a query result. Views are not suitable / developed for operations like this one.

How to render an ASP.NET MVC view as a string?

I found a better way to render razor view page when I got error with the methods above, this solution for both web form environment and mvc environment. No controller is needed.

Here is the code example, in this example I simulated a mvc action with an async http handler:

    /// <summary>
    /// Enables processing of HTTP Web requests asynchronously by a custom HttpHandler that implements the IHttpHandler interface.
    /// </summary>
    /// <param name="context">An HttpContext object that provides references to the intrinsic server objects.</param>
    /// <returns>The task to complete the http request.</returns>
    protected override async Task ProcessRequestAsync(HttpContext context)
    {
        if (this._view == null)
        {
            this.OnError(context, new FileNotFoundException("Can not find the mvc view file.".Localize()));
            return;
        }
        object model = await this.LoadModelAsync(context);
        WebPageBase page = WebPageBase.CreateInstanceFromVirtualPath(this._view.VirtualPath);
        using (StringWriter sw = new StringWriter())
        {
            page.ExecutePageHierarchy(new WebPageContext(new HttpContextWrapper(context), page, model), sw);
            await context.Response.Output.WriteAsync(sw.GetStringBuilder().ToString());
        }
    }

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

How can I close a window with Javascript on Mozilla Firefox 3?

function closeWindow() {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
    alert("This will close the window");
    window.open('','_self');
    window.close();
}

closeWindow();

How to auto-generate a C# class file from a JSON string

Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.

Visual Studio 2013 onwards have this built-in.

Visual Studio Paste JSON as Classes screenshot (Image courtesy: robert.muehsig)

Creating a new database and new connection in Oracle SQL Developer

This tutorial should help you:

Getting Started with Oracle SQL Developer

See the prerequisites:

  1. Install Oracle SQL Developer. You already have it.
  2. Install the Oracle Database. Download available here.
  3. Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:

    alter user hr identified by hr account unlock;

  4. Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.


Another version from May 2011: Getting Started with Oracle SQL Developer


For more info check this related question:

How to create a new database after initally installing oracle database 11g Express Edition?

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

For completeness, the answer to Asp.Net Core tag in web.config causes failure may also be the solution to the problem here. If the .NET Core Windows Server Hosting bundle is not installed then IIS cannot recognize the aspNetCore section in web.config. https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1#install-the-net-core-hosting-bundle claims to be a direct download to the current version.

How do I get a div to float to the bottom of its container?

This puts a fixed div at the bottom of the page and fixes to the bottom as you scroll down

#div {
    left: 0;
    position: fixed;
    text-align: center;
    bottom: 0;
    width: 100%;
}

HTTP Error 404 when running Tomcat from Eclipse

I had this or a similar problem after installing Tomcat.

The other answers didn't quite work, but got me on the right path. I answered this at https://stackoverflow.com/a/20762179/3128838 after discovering a YouTube video showing the exact problem I was having.

Relative URLs in WordPress

I agree with Rup. I guess the main reason is to avoid confusion on relative paths. I think wordpress can work from scratch with relative paths but the problem might come when using multiple plugins, how the theme is configured etc.

I've once used this plugin for relative paths, when working on testing servers:

Root Relative URLs
Converts all URLs to root-relative URLs for hosting the same site on multiple IPs, easier production migration and better mobile device testing.

Determining the last row in a single column

Here's an alternative way of solving this. It uses a while loop but takes into consideration empty gaps between rows.

function getLastRow (column) {
  var iLastRow = ss.getActiveSheet().getMaxRows();
  var aValues = ss.getActiveSheet().getRange(column + ":" + column).getValues();
  var row = "";
  while(row == ""){
    row = aValues[iLastRow-1];
    iLastRow--;
  }
  return iLastRow;
}

Regular expression replace in C#

Add the following 2 lines

var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);

If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"

How to check if an int is a null

A primitive int cannot be null. If you need null, use Integer instead.

Rename a dictionary key

@helloswift123 I like your function. Here is a modification to rename multiple keys in a single call:

def rename(d, keymap):
    """
    :param d: old dict
    :type d: dict
    :param keymap: [{:keys from-keys :values to-keys} keymap]
    :returns: new dict
    :rtype: dict
    """
    new_dict = {}
    for key, value in zip(d.keys(), d.values()):
        new_key = keymap.get(key, key)
        new_dict[new_key] = d[key]
    return new_dict

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

Differences between fork and exec

enter image description herefork():

It creates a copy of running process. The running process is called parent process & newly created process is called child process. The way to differentiate the two is by looking at the returned value:

  1. fork() returns the process identifier (pid) of the child process in the parent

  2. fork() returns 0 in the child.

exec():

It initiates a new process within a process. It loads a new program into the current process, replacing the existing one.

fork() + exec():

When launching a new program is to firstly fork(), creating a new process, and then exec() (i.e. load into memory and execute) the program binary it is supposed to run.

int main( void ) 
{
    int pid = fork();
    if ( pid == 0 ) 
    {
        execvp( "find", argv );
    }

    //Put the parent to sleep for 2 sec,let the child finished executing 
    wait( 2 );

    return 0;
}

How to include view/partial specific styling in AngularJS

'use strict'; angular.module('app') .run( [ '$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; } ] ) .config( [ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

            $urlRouterProvider
                .otherwise('/app/dashboard');
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: 'views/layout.html'
                })
                .state('app.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard.html',
                    ncyBreadcrumb: {
                        label: 'Dashboard',
                        description: ''
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                .state('ram', {
                    abstract: true,
                    url: '/ram',
                    templateUrl: 'views/layout-ram.html'
                })
                .state('ram.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard-ram.html',
                    ncyBreadcrumb: {
                        label: 'test'
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                 );

How do I set multipart in axios with react?

ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.

fileUpload = (e) => {
    let data = e.target.files
    if(e.target.files[0]!=null){
        this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
    }
}

here fileUpload is a different js file which accepts two params like this

export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);

return dispatch => {
    axios.put(BaseUrl.RestUrl + "ur/url", formData)
        .then(response => {
            callback(response.data);
        }).catch(error => {
         console.log("*****  "+error)
    });
}

}

don't forget to bind method in the constructor. Let me know if you need more help in this.

What is the difference between JDK and JRE?

JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.

Java Virtual Machine (JVM) is a run-time system that executes Java bytecode.

JRE is the environment (standard libraries and JVM) required to run Java applications.

The JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.

How do I refresh a DIV content?

You can use jQuery to achieve this using simple $.get method. .html work like innerHtml and replace the content of your div.

$.get("/YourUrl", {},
      function (returnedHtml) {
      $("#here").html(returnedHtml);
});

And call this using javascript setInterval method.

Check whether specific radio button is checked

You should remove the '@' before 'name'; it's not needed anymore (for current jQuery versions).

You're want to return all checked elements with name 'test2', but you don't have any elements with that name, you're using an id of 'test2'.

If you're going to use IDs, just try:

return $('#test2').attr('checked');

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.

How to change Apache Tomcat web server port number

1) Locate server.xml in {Tomcat installation folder}\ conf \ 2) Find following similar statement

       <!-- Define a non-SSL HTTP/1.1 Connector on port 8180 -->
      <Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

For example

<Connector port="8181" protocol="HTTP/1.1" 
           connectionTimeout="20000" 
           redirectPort="8443" />

Edit and save the server.xml file. Restart Tomcat. Done

Further reference: http://www.mkyong.com/tomcat/how-to-change-tomcat-default-port/

Maximum number of threads per process in Linux?

In practical terms, the limit is usually determined by stack space. If each thread gets a 1MB stack (I can't remember if that is the default on Linux), then you a 32-bit system will run out of address space after 3000 threads (assuming that the last gb is reserved to the kernel).

However, you'll most likely experience terrible performance if you use more than a few dozen threads. Sooner or later, you get too much context-switching overhead, too much overhead in the scheduler, and so on. (Creating a large number of threads does little more than eat a lot of memory. But a lot of threads with actual work to do is going to slow you down as they're fighting for the available CPU time)

What are you doing where this limit is even relevant?

Single TextView with multiple colored text

Use SpannableBuilder class instead of HTML formatting where it possible because it more faster then HTML format parsing. See my own benchmark "SpannableBuilder vs HTML" on Github Thanks!

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Array Size (Length) in C#

yourArray.Length :)

Convert InputStream to byte array in Java

You're doing an extra copy if you use ByteArrayOutputStream. If you know the length of the stream before you start reading it (e.g. the InputStream is actually a FileInputStream, and you can call file.length() on the file, or the InputStream is a zipfile entry InputStream, and you can call zipEntry.length()), then it's far better to write directly into the byte[] array -- it uses half the memory, and saves time.

// Read the file contents into a byte[] array
byte[] buf = new byte[inputStreamLength];
int bytesRead = Math.max(0, inputStream.read(buf));

// If needed: for safety, truncate the array if the file may somehow get
// truncated during the read operation
byte[] contents = bytesRead == inputStreamLength ? buf
                  : Arrays.copyOf(buf, bytesRead);

N.B. the last line above deals with files getting truncated while the stream is being read, if you need to handle that possibility, but if the file gets longer while the stream is being read, the contents in the byte[] array will not be lengthened to include the new file content, the array will simply be truncated to the old length inputStreamLength.

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Answers suggesting to disable CURLOPT_SSL_VERIFYPEER should not be accepted. The question is "Why doesn't it work with cURL", and as correctly pointed out by Martijn Hols, it is dangerous.

The error is probably caused by not having an up-to-date bundle of CA root certificates. This is typically a text file with a bunch of cryptographic signatures that curl uses to verify a host’s SSL certificate.

You need to make sure that your installation of PHP has one of these files, and that it’s up to date (otherwise download one here: http://curl.haxx.se/docs/caextract.html).

Then set in php.ini:

curl.cainfo = <absolute_path_to> cacert.pem

If you are setting it at runtime, use:

curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");

Jackson: how to prevent field serialization

You can mark it as @JsonIgnore.

With 1.9, you can add @JsonIgnore for getter, @JsonProperty for setter, to make it deserialize but not serialize.

How do I detect if a user is already logged in Firebase?

One another way is to use the same thing what firebase uses.

For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.

enter image description here

ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)

How to change scroll bar position with CSS?

Here is another way, by rotating element with the scrollbar for 180deg, wrapping it's content into another element, and rotating that wrapper for -180deg. Check the snippet below

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 2px solid black;_x000D_
  margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
  direction: rtl;_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
  direction: ltr;_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
  direction: rtl;_x000D_
  transform: rotate(180deg);_x000D_
  overflow-y: hidden;_x000D_
  overflow-x: scroll;_x000D_
  background: tomato;_x000D_
  padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
  direction: ltr;_x000D_
  display: inline-block;_x000D_
  transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
  <p>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert Decimal to Varchar

Here's one way:

create table #work
(
  something decimal(8,3) not null 
)

insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )

select convert(varchar,convert(decimal(8,2),something))
from #work

if you want it right-aligned, something like this should do you:

select str(something,8,2) from #work

set font size in jquery

Not saying this is better, just another way:

$("#elem")[0].style.fontSize="20px";

How to stop text from taking up more than 1 line?

Just to be crystal clear, this works nicely with paragraphs and headers etc. You just need to specify display: block.

For instance:

<h5 style="display: block; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
  This is a really long title, but it won't exceed the parent width
</h5>

(forgive the inline styles)

Print page numbers on pages when printing html

Can you try this, you can use content: counter(page);

     @page {
       @bottom-left {
            content: counter(page) "/" counter(pages);
        }
     }

Ref: http://www.w3.org/TR/CSS21/generate.html#counters

http://www.princexml.com/doc/9.0/page-numbers/

How to find which version of TensorFlow is installed in my system?

If you're using anaconda distribution of Python,

$ conda list | grep tensorflow
tensorflow    1.0.0       py35_0    conda-forge

To check it using Jupyter Notebook (IPython Notebook)

In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'

Multiline text in JLabel

why you are giving complex things...you can just do it by putting "\n" instead of html tags

How to center links in HTML

p is not how you put text in a. That is the problem. The only solution is to put the text between <a> and </a>. For example:

<a href="https://stackoverflow.com/posts/64201994/edit" style="text-align:center;">Stack Overflow</a>

How do I get list of all tables in a database using TSQL?

SELECT * FROM information_schema.tables
where TABLE_TYPE = 'BASE TABLE'

SQL Server 2012

How do I convert from int to String?

The other way I am aware of is from the Integer class:

Integer.toString(int n);
Integer.toString(int n, int radix);

A concrete example (though I wouldn't think you need any):

String five = Integer.toString(5); // returns "5"

It also works for other primitive types, for instance Double.toString.

See here for more details.

Replace all particular values in a data frame

We can use data.table to get it quickly. First create df without factors,

df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)), stringsAsFactors=F)

Now you can use

setDT(df)
for (jj in 1:ncol(df)) set(df, i = which(df[[jj]]==""), j = jj, v = NA)

and you can convert it back to a data.frame

setDF(df)

If you only want to use data.frame and keep factors it's more difficult, you need to work with

levels(df$value)[levels(df$value)==""] <- NA

where value is the name of every column. You need to insert it in a loop.

How to view the current heap size that an application is using?

You can do it by MXBeans

public class Check {
    public static void main(String[] args) {
        MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
        MemoryUsage heapMemoryUsage = memBean.getHeapMemoryUsage();

        System.out.println(heapMemoryUsage.getMax()); // max memory allowed for jvm -Xmx flag (-1 if isn't specified)
        System.out.println(heapMemoryUsage.getCommitted()); // given memory to JVM by OS ( may fail to reach getMax, if there isn't more memory)
        System.out.println(heapMemoryUsage.getUsed()); // used now by your heap
        System.out.println(heapMemoryUsage.getInit()); // -Xms flag

        // |------------------ max ------------------------| allowed to be occupied by you from OS (less than xmX due to empty survival space)
        // |------------------ committed -------|          | now taken from OS
        // |------------------ used --|                    | used by your heap

    }
}

But remember it is equivalent to Runtime.getRuntime() (took depicted schema from here)

memoryMxBean.getHeapMemoryUsage().getUsed()      <=> runtime.totalMemory() - runtime.freeMemory()
memoryMxBean.getHeapMemoryUsage().getCommitted() <=> runtime.totalMemory()
memoryMxBean.getHeapMemoryUsage().getMax()       <=> runtime.maxMemory()

from javaDoc

init - represents the initial amount of memory (in bytes) that the Java virtual machine requests from the operating system for memory management during startup. The Java virtual machine may request additional memory from the operating system and may also release memory to the system over time. The value of init may be undefined.

used - represents the amount of memory currently used (in bytes).

committed - represents the amount of memory (in bytes) that is guaranteed to be available for use by the Java virtual machine. The amount of committed memory may change over time (increase or decrease). The Java virtual machine may release memory to the system and committed could be less than init. committed will always be greater than or equal to used.

max - represents the maximum amount of memory (in bytes) that can be used for memory management. Its value may be undefined. The maximum amount of memory may change over time if defined. The amount of used and committed memory will always be less than or equal to max if max is defined. A memory allocation may fail if it attempts to increase the used memory such that used > committed even if used <= max would still be true (for example, when the system is low on virtual memory).

    +----------------------------------------------+
    +////////////////           |                  +
    +////////////////           |                  +
    +----------------------------------------------+

    |--------|
       init
    |---------------|
           used
    |---------------------------|
              committed
    |----------------------------------------------|
                        max

As additional note, maxMemory is less than -Xmx because there is necessity at least in one empty survival space, which can't be used for heap allocation.

also it is worth to to take a look at here and especially here

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {
     console.log(product.product_desc)
}

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];
    console.log(product.product_desc);
}

Performing a Stress Test on Web Application?

I've used JMeter. Besides testing the web server you can also test your database backend, messaging services and email servers.