Programs & Examples On #Cometd

CometD is a scalable HTTP-based event routing bus that uses a Ajax Push technology pattern known as Comet. The term 'Comet' was coined by Alex Russell in his post Comet: Low Latency Data for the Browser. See http://cometd.org/

Maven2: Missing artifact but jars are in place

Wow, this had me tearing my hair out, banging my head against walls, tables and other things. I had the same or a similar issue as the OP where it was either missing / not downloading the jar files or downloading them, but not including them in the Maven dependencies with the same error message. My limited knowledge of java packaging and maven probably didn't help.

For me the problem seems to have been caused by the Dependency Type "bundle" (but I don't know how or why). I was using the Add Dependency dialog in Eclipse Mars on the pom.xml, which allows you to search and browse the central repository. I was searching and adding a dependency to jackson-core libraries, picking the latest version, available as a bundle. This kept failing.

So finally, I changed the dependency properties form bundle to jar (again using the dependency properties window), which finally downloaded and referenced the dependencies properly after saving the changes.

Hibernate: How to fix "identifier of an instance altered from X to Y"?

Make sure you aren't trying to use the same User object more than once while changing the ID. In other words, if you were doing something in a batch type operation:

User user = new User();  // Using the same one over and over, won't work
List<Customer> customers = fetchCustomersFromSomeService();
for(Customer customer : customers) {
 // User user = new User(); <-- This would work, you get a new one each time
 user.setId(customer.getId());
 user.setName(customer.getName());
 saveUserToDB(user);
}

How do I implement basic "Long Polling"?

It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).

Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)

msgsrv.php

<?php
if(rand(1,3) == 1){
    /* Fake an error */
    header("HTTP/1.0 404 Not Found");
    die();
}

/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>

Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)

Then, in Javascript, you request the above file (msg_srv.php), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)

What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php file.. If it succeeds, we append the message to the #messages div, then after 1 second we call the waitForMsg function again, which triggers the wait.

The 1 second setTimeout() is a really basic rate-limiter, it works fine without this, but if msgsrv.php always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.

If the page errors, it appends the error to the #messages div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)

The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required

Anyway, the long_poller.htm code, using the jQuery framework:

<html>
<head>
    <title>BargePoller</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>

    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            BargePoll message requester!
        </div>
    </div>
</body>
</html>

How to list the properties of a JavaScript object?

Under browsers supporting js 1.8:

[i for(i in obj)]

How to get current working directory in Java?

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

make a header full screen (width) css

The best way to make the header full screen is set height to be 100vh

#header{
height: 100vh;
}

Difference between List, List<?>, List<T>, List<E>, and List<Object>

The notation List<?> means "a list of something (but I'm not saying what)". Since the code in test works for any kind of object in the list, this works as a formal method parameter.

Using a type parameter (like in your point 3), requires that the type parameter be declared. The Java syntax for that is to put <T> in front of the function. This is exactly analogous to declaring formal parameter names to a method before using the names in the method body.

Regarding List<Object> not accepting a List<String>, that makes sense because a String is not Object; it is a subclass of Object. The fix is to declare public static void test(List<? extends Object> set) .... But then the extends Object is redundant, because every class directly or indirectly extends Object.

Very Long If Statement in Python

Here is the example directly from PEP 8 on limiting line length:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

appending list but error 'NoneType' object has no attribute 'append'

list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work

Redirect to specified URL on PHP script completion?

If "SOMETHING DONE" doesn't invovle any output via echo/print/etc, then:

<?php
   // SOMETHING DONE

   header('Location: http://stackoverflow.com');
?>

to call onChange event after pressing Enter key

According to React Doc, you could listen to keyboard events, like onKeyPress or onKeyUp, not onChange.

var Input = React.createClass({
  render: function () {
    return <input type="text" onKeyDown={this._handleKeyDown} />;
  },
  _handleKeyDown: function(e) {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }
});

Update: Use React.Component

Here is the code using React.Component which does the same thing

class Input extends React.Component {
  _handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }

  render() {
    return <input type="text" onKeyDown={this._handleKeyDown} />
  }
}

Here is the jsfiddle.

Update 2: Use a functional component

const Input = () => {
  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      console.log('do validate')
    }
  }

  return <input type="text" onKeyDown={handleKeyDown} />
}

Best way to read a large file into a byte array in C#?

Depending on the frequency of operations, the size of the files, and the number of files you're looking at, there are other performance issues to take into consideration. One thing to remember, is that each of your byte arrays will be released at the mercy of the garbage collector. If you're not caching any of that data, you could end up creating a lot of garbage and be losing most of your performance to % Time in GC. If the chunks are larger than 85K, you'll be allocating to the Large Object Heap(LOH) which will require a collection of all generations to free up (this is very expensive, and on a server will stop all execution while it's going on). Additionally, if you have a ton of objects on the LOH, you can end up with LOH fragmentation (the LOH is never compacted) which leads to poor performance and out of memory exceptions. You can recycle the process once you hit a certain point, but I don't know if that's a best practice.

The point is, you should consider the full life cycle of your app before necessarily just reading all the bytes into memory the fastest way possible or you might be trading short term performance for overall performance.

Capture Image from Camera and Display in Activity

You can use this code to onClick listener (you can use ImageView or button)

image.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, 1);
            }
        }
    });

To display in your imageView

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        bitmap = (Bitmap) extras.get("data");
        image.setImageBitmap(bitmap);

    }
}

Note: Insert this to the manifest

<uses-feature android:name="android.hardware.camera" android:required="true" />

Passing a method as a parameter in Ruby

I would recommend to use ampersand to have an access to named blocks within a function. Following the recommendations given in this article you can write something like this (this is a real scrap from my working program):

  # Returns a valid hash for html form select element, combined of all entities
  # for the given +model+, where only id and name attributes are taken as
  # values and keys correspondingly. Provide block returning boolean if you
  # need to select only specific entities.
  #
  # * *Args*    :
  #   - +model+ -> ORM interface for specific entities'
  #   - +&cond+ -> block {|x| boolean}, filtering entities upon iterations
  # * *Returns* :
  #   - hash of {entity.id => entity.name}
  #
  def make_select_list( model, &cond )
    cond ||= proc { true } # cond defaults to proc { true }
    # Entities filtered by cond, followed by filtration by (id, name)
    model.all.map do |x|
      cond.( x ) ? { x.id => x.name } : {}
    end.reduce Hash.new do |memo, e| memo.merge( e ) end
  end

Afterwerds, you can call this function like this:

@contests = make_select_list Contest do |contest|
  logged_admin? or contest.organizer == @current_user
end

If you don't need to filter your selection, you simply omit the block:

@categories = make_select_list( Category ) # selects all categories

So much for the power of Ruby blocks.

How to bind 'touchstart' and 'click' events but not respond to both?

I gave an answer there and I demonstrate with a jsfiddle. You can check for different devices and report it.

Basically I use a kind of event lock with some functions that serve it:

/*
 * Event lock functions
 * ====================
 */
function getEventLock(evt, key){
   if(typeof(eventLock[key]) == 'undefined'){
      eventLock[key] = {};
      eventLock[key].primary = evt.type;
      return true;
   }
   if(evt.type == eventLock[key].primary)
      return true;
   else
      return false;
}

function primaryEventLock(evt, key){
   eventLock[key].primary = evt.type;
}

Then, in my event handlers I start by a request to my lock:

/*
 * Event handlers
 * ==============
 */
$("#add").on("touchstart mousedown", addStart);
$("#add").on("touchend mouseup", addEnd);
function addStart(evt){
   // race condition between 'mousedown' and 'touchstart'
   if(!getEventLock(evt, 'add'))
      return;

   // some logic
   now = new Date().getTime();
   press = -defaults.pressDelay;
   task();

   // enable event lock and(?) event repetition
   pids.add = setTimeout(closure, defaults.pressDelay);

   function closure(){
        // some logic(?): comment out to disable repetition
      task();

      // set primary input device
      primaryEventLock(evt, 'add');

      // enable event repetition
      pids.add = setTimeout(closure, defaults.pressDelay);
   }
}
function addEnd(evt){
      clearTimeout(pids.add);
}

I have to stress that the problem is not to respond simply at a event but to NOT respond on both.

Finally, at jsfiddle there is a link to an updated version where I introduce minimal impact at existing code by adding just a simple call to my event lock library both at event start & end handlers along with 2 scope variables eventLock and eventLockDelay.

Detect if HTML5 Video element is playing

var video_switch  = 0;

function play() {

    var media = document.getElementById('video');

    if (video_switch == 0)
    {
        media.play();
        video_switch = 1;
    }
    else if (video_switch == 1)
    {
        media.pause();
        video_switch = 0;
    }
}

Exception: There is already an open DataReader associated with this Connection which must be closed first

You are trying to to an Insert (with ExecuteNonQuery()) on a SQL connection that is used by this reader already:

while (myReader.Read())

Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.

Controlling fps with requestAnimationFrame?

The simplest way


const FPS = 30;
let lastTimestamp = 0;


function update(timestamp) {
  requestAnimationFrame(update);
  if (timestamp - lastTimestamp < 1000 / FPS) return;
  
  
   /* <<< PUT YOUR CODE HERE >>>  */

 
  lastTimestamp = timestamp;
}


update();

Bulk insert with SQLAlchemy ORM

Piere's answer is correct but one issue is that bulk_save_objects by default does not return the primary keys of the objects, if that is of concern to you. Set return_defaults to True to get this behavior.

The documentation is here.

foos = [Foo(bar='a',), Foo(bar='b'), Foo(bar='c')]
session.bulk_save_objects(foos, return_defaults=True)
for foo in foos:
    assert foo.id is not None
session.commit()

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

My issue was solved by simply refreshing the modules View > Maven Projects. There is refresh icon which refreshes your entire project(s)

How I got this error : I imported a project (Let's call this A which is main project) first and added the remaining projects (B,C,D etc) as modules to this one as I needed all my projects to be shown in one package folder. I deleted the old (A) Project and cloned it again from repo. The IntelliJ reloaded the (A) project but when I try to run, the project wasn't compiling saying "Warning:No JDK specified for module 'B'".

How to check for the type of a template parameter?

std::is_same() is only available since C++11. For pre-C++11 you can use typeid():

template <typename T>
void foo()
{
    if (typeid(T) == typeid(animal)) { /* ... */ }
}

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

Changing 'java.library.path' variable at runtime is not enough because it is read only once by JVM. You have to reset it like:

System.setProperty("java.library.path", path);
//set sys_paths to null
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);

Please, take a loot at: Changing Java Library Path at Runtime.

DropDownList in MVC 4 with Razor

If you're using ASP.net 5 (MVC 6) or later then you can use the new Tag Helpers for a very nice syntax:

<select asp-for="tipo">
    <option value="Exemplo1">Exemplo1</option>
    <option value="Exemplo2">Exemplo2</option>
    <option value="Exemplo3">Exemplo3</option>
</select>

How to add minutes to my Date

you can use DateUtils class in org.apache.commons.lang3.time package

int addMinuteTime = 5;
Date targetTime = new Date(); //now
targetTime = DateUtils.addMinutes(targetTime, addMinuteTime); //add minute

Warning: date_format() expects parameter 1 to be DateTime

try this

$start_date = date_create($_POST['start_date']);
$start_date = date_format($start_date,"Y-m-d H:i:s");

How can I get the source code of a Python function?

To expand on runeh's answer:

>>> def foo(a):
...    x = 2
...    return x + a

>>> import inspect

>>> inspect.getsource(foo)
u'def foo(a):\n    x = 2\n    return x + a\n'

print inspect.getsource(foo)
def foo(a):
   x = 2
   return x + a

EDIT: As pointed out by @0sh this example works using ipython but not plain python. It should be fine in both, however, when importing code from source files.

how to toggle (hide/show) a table onClick of <a> tag in java script

Simple using jquery

<script>
$(document).ready(function() {
    $('#loginLink').click(function() {
    $('#loginTable').toggle('slow');
    });
})
</script>

Hibernate Delete query

To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -

Hibernate Object States

Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.

Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Detached - A detached instance is an object that has been persistent, but its Session has been closed.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview

Transaction Write-Behind

The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.

  • To perform batch inserts and updates.
  • To propagate only the last change. If an object is updated more than once, it still fires only one update statement.

http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html

First Level Cache

Hibernate has something called 'First Level Cache'. Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. This is where it tracks changes to various objects.

Hibernate Intercepters and Object Lifecycle Listeners -

The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069


This section Updated

Cascading

Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete' from parent to child association will result in deletion of all children when a parent is deleted.

So, why are these important.

To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.

That's why hibernate (sometimes) issues a 'SELECT' statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.

Why does hibernate issue the 'SELECT' statement only sometimes?

Hibernate issues a 'SELECT' statement to determine what state the object is in. If the select statement returns an object, the object is in detached state and if it does not return an object, the object is in transient state.

Coming to your scenario -

Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached and then re-attches it to the session and processes delete lifecycle.

Update - Since you are explicitly calling 'Update' instead of 'SaveOrUpdate', hibernate blindly assumes that the object is in detached state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.

SaveOrUpdate - If you call 'SaveOrUpdate', hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached state. If the object is in transient state, it processes the 'insert' lifecycle and if the object is in detached state, it processes the 'Update' lifecycle.

CSS/HTML: Create a glowing border around an Input Field

input[type="text"]{
   @include transition(all 0.30s ease-in-out);
  outline: none;
  padding: 3px 0px 3px 3px;
  margin: 5px 1px 3px 0px;
  border: 1px solid #DDDDDD;
}
input[type="text"]:focus{
  @include box-shadow(0 0 5px rgba(81, 203, 238, 1));
  -webkit-box-shadow: 0px 0px 5px #007eff;  
  -moz-box-shadow: 0px 0px 5px #007eff;  
  box-shadow: 0px 0px 5px #007eff;
}

How to checkout a specific Subversion revision from the command line?

svn checkout to revision where your repository is on another server

Use svn log command to find out which revisions are available:

svn log

Which prints:

------------------------------------------------------------------------
r762 | machines | 2012-12-02 13:00:16 -0500 (Sun, 02 Dec 2012) | 2 lines

------------------------------------------------------------------------
r761 | machines | 2012-12-02 12:59:40 -0500 (Sun, 02 Dec 2012) | 2 lines

Note the number r761. Here is the command description:

svn export http://url-to-your-file@761 /tmp/filename

I used this command specifically:

svn export svn+ssh://[email protected]/home1/oct/calc/calcFeatures.m@761 calcFeatures.m

Which causes calcFeatures.m revision 761 to be checked out to the current directory.

How to delete rows in tables that contain foreign keys to other tables

Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table

What is VanillaJS?

"Vanilla JS” is an expression that got popular after the publishing of a satire website in 2012 (http://vanilla-js.com/). There’s a section covering its story/meaning in this post.

So why the joke? It kind of came as a modern response to the old school knee-jerk reflex of relying on jQuery and additional JS libraries. With the ECMAScript spec and modern browsers capabilities, the need to bypass plain JS with external libraries to maintain consistency across browsers just isn’t there anymore. Here’s a site that shows you how true this is with concrete examples: http://youmightnotneedjquery.com/

__FILE__, __LINE__, and __FUNCTION__ usage in C++

Personally, I'm reluctant to use these for anything but debugging messages. I have done it, but I try not to show that kind of information to customers or end users. My customers are not engineers and are sometimes not computer savvy. I might log this info to the console, but, as I said, reluctantly except for debug builds or for internal tools. I suppose it does depend on the customer base you have, though.

How to convert an Image to base64 string in java?

this did it for me. you can vary the options for the output format to Base64.Default whatsoever.

// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

Path of currently executing powershell script

Split-Path $MyInvocation.MyCommand.Path -Parent

Java "user.dir" property - what exactly does it mean?

System.getProperty("user.dir") fetches the directory or path of the workspace for the current project

How do I set multipart in axios with react?

If you are sending alphanumeric data try changing

'Content-Type': 'multipart/form-data'

to

'Content-Type': 'application/x-www-form-urlencoded'

If you are sending non-alphanumeric data try to remove 'Content-Type' at all.

If it still does not work, consider trying request-promise (at least to test whether it is really axios problem or not)

Database, Table and Column Naming Conventions?

I know this is late to the game, and the question has been answered very well already, but I want to offer my opinion on #3 regarding the prefixing of column names.

All columns should be named with a prefix that is unique to the table they are defined in.

E.g. Given tables "customer" and "address", let's go with prefixes of "cust" and "addr", respectively. "customer" would have "cust_id", "cust_name", etc. in it. "address" would have "addr_id", "addr_cust_id" (FK back to customer), "addr_street", etc. in it.

When I was first presented with this standard, I was dead-set against it; I hated the idea. I couldn't stand the idea of all that extra typing and redundancy. Now I've had enough experience with it that I'd never go back.

The result of doing this is that all of the columns in your database schema are unique. There is one major benefit to this, which trumps all arguments against it (in my opinion, of course):

You can search your entire code base and reliably find every line of code that touches a particular column.

The benefit from #1 is incredibly huge. I can deprecate a column and know exactly what files need to be updated before the column can safely be removed from the schema. I can change the meaning of a column and know exactly what code needs to be refactored. Or I can simply tell if data from a column is even being used in a particular portion of the system. I can't count the number of times this has turned a potentially huge project into a simple one, nor the amount of hours we've saved in development work.

Another, relatively minor benefit to it is that you only have to use table-aliases when you do a self join:

SELECT cust_id, cust_name, addr_street, addr_city, addr_state
    FROM customer
        INNER JOIN address ON addr_cust_id = cust_id
    WHERE cust_name LIKE 'J%';

What is the best way to redirect a page using React Router?

You can also use react router dom library useHistory;

`
import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
`

https://reactrouter.com/web/api/Hooks/usehistory

Why use the INCLUDE clause when creating an index?

This discussion is missing out on the important point: The question is not if the "non-key-columns" are better to include as index-columns or as included-columns.

The question is how expensive it is to use the include-mechanism to include columns that are not really needed in index? (typically not part of where-clauses, but often included in selects). So your dilemma is always:

  1. Use index on id1, id2 ... idN alone or
  2. Use index on id1, id2 ... idN plus include col1, col2 ... colN

Where: id1, id2 ... idN are columns often used in restrictions and col1, col2 ... colN are columns often selected, but typically not used in restrictions

(The option to include all of these columns as part of the index-key is just always silly (unless they are also used in restrictions) - cause it would always be more expensive to maintain since the index must be updated and sorted even when the "keys" have not changed).

So use option 1 or 2?

Answer: If your table is rarely updated - mostly inserted into/deleted from - then it is relatively inexpensive to use the include-mechanism to include some "hot columns" (that are often used in selects - but not often used on restrictions) since inserts/deletes require the index to be updated/sorted anyway and thus little extra overhead is associated with storing off a few extra columns while already updating the index. The overhead is the extra memory and CPU used to store redundant info on the index.

If the columns you consider to add as included-columns are often updated (without the index-key-columns being updated) - or - if it is so many of them that the index becomes close to a copy of your table - use option 1 I'd suggest! Also if adding certain include-column(s) turns out to make no performance-difference - you might want to skip the idea of adding them:) Verify that they are useful!

The average number of rows per same values in keys (id1, id2 ... idN) can be of some importance as well.

Notice that if a column - that is added as an included-column of index - is used in the restriction: As long as the index as such can be used (based on restriction against index-key-columns) - then SQL Server is matching the column-restriction against the index (leaf-node-values) instead of going the expensive way around the table itself.

Text to speech(TTS)-Android

A minimalistic example to quickly test the TTS system:

private TextToSpeech textToSpeechSystem;

@Override
protected void onStart() {
  super.onStart();
  textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                String textToSay = "Hello world, this is a test message!";
                textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
            }
        }
   });
}

If you don't use localized messages textToSpeechSystem.setLanguage(..) is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough

Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech

How to pass argument to Makefile from command line?

don't try to do this

$ make action value1 value2

instead create script:

#! /bin/sh
# rebuild if necessary
make
# do action with arguments
action "$@"

and do this:

$ ./buildthenaction.sh value1 value2

for more explanation why do this and caveats of makefile hackery read my answer to another very similar but seemingly not duplicate question: Passing arguments to "make run"

CSS:Defining Styles for input elements inside a div

When you say "called" I'm going to assume you mean an ID tag.

To make it cross-brower, I wouldn't suggest using the CSS3 [], although it is an option. This being said, give each of your textboxes a class like "tb" and the radio button "rb".

Then:

#divContainer .tb { width: 150px }
#divContainer .rb { width: 20px }

This assumes you are using the same classes elsewhere, if not, this will suffice:

.tb { width: 150px }
.rb { width: 20px }

As @David mentioned, to access anything within the division itself:

#divContainer [element] { ... }

Where [element] is whatever HTML element you need.

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

You can set the line-height in pixels instead of percentage. Is that what you mean?

How to kill a nodejs process in Linux?

sudo netstat -lpn |grep :'3000'

3000 is port i was looking for, After first command you will have Process ID for that port

kill -9 1192

in my case 1192 was process Id of process running on 3000 PORT use -9 for Force kill the process

Case in Select Statement

I think these could be helpful for you .

Using a SELECT statement with a simple CASE expression

Within a SELECT statement, a simple CASE expression allows for only an equality check; no other comparisons are made. The following example uses the CASE expression to change the display of product line categories to make them more understandable.

USE AdventureWorks2012;
GO
SELECT   ProductNumber, Category =
      CASE ProductLine
         WHEN 'R' THEN 'Road'
         WHEN 'M' THEN 'Mountain'
         WHEN 'T' THEN 'Touring'
         WHEN 'S' THEN 'Other sale items'
         ELSE 'Not for sale'
      END,
   Name
FROM Production.Product
ORDER BY ProductNumber;
GO

Using a SELECT statement with a searched CASE expression

Within a SELECT statement, the searched CASE expression allows for values to be replaced in the result set based on comparison values. The following example displays the list price as a text comment based on the price range for a product.

USE AdventureWorks2012;
GO
SELECT   ProductNumber, Name, "Price Range" = 
      CASE 
         WHEN ListPrice =  0 THEN 'Mfg item - not for resale'
         WHEN ListPrice < 50 THEN 'Under $50'
         WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
         WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
         ELSE 'Over $1000'
      END
FROM Production.Product
ORDER BY ProductNumber ;
GO

Using CASE in an ORDER BY clause

The following examples uses the CASE expression in an ORDER BY clause to determine the sort order of the rows based on a given column value. In the first example, the value in the SalariedFlag column of the HumanResources.Employee table is evaluated. Employees that have the SalariedFlag set to 1 are returned in order by the BusinessEntityID in descending order. Employees that have the SalariedFlag set to 0 are returned in order by the BusinessEntityID in ascending order. In the second example, the result set is ordered by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows.

SELECT BusinessEntityID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN BusinessEntityID END DESC
        ,CASE WHEN SalariedFlag = 0 THEN BusinessEntityID END;
GO


SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL
ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName
         ELSE CountryRegionName END;

Using CASE in an UPDATE statement

The following example uses the CASE expression in an UPDATE statement to determine the value that is set for the column VacationHours for employees with SalariedFlag set to 0. When subtracting 10 hours from VacationHours results in a negative value, VacationHours is increased by 40 hours; otherwise, VacationHours is increased by 20 hours. The OUTPUT clause is used to display the before and after vacation values.

USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET VacationHours = 
    ( CASE
         WHEN ((VacationHours - 10.00) < 0) THEN VacationHours + 40
         ELSE (VacationHours + 20.00)
       END
    )
OUTPUT Deleted.BusinessEntityID, Deleted.VacationHours AS BeforeValue, 
       Inserted.VacationHours AS AfterValue
WHERE SalariedFlag = 0; 

Using CASE in a HAVING clause

The following example uses the CASE expression in a HAVING clause to restrict the rows returned by the SELECT statement. The statement returns the the maximum hourly rate for each job title in the HumanResources.Employee table. The HAVING clause restricts the titles to those that are held by men with a maximum pay rate greater than 40 dollars or women with a maximum pay rate greater than 42 dollars.

USE AdventureWorks2012;
GO
SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID
GROUP BY JobTitle
HAVING (MAX(CASE WHEN Gender = 'M' 
        THEN ph1.Rate 
        ELSE NULL END) > 40.00
     OR MAX(CASE WHEN Gender  = 'F' 
        THEN ph1.Rate  
        ELSE NULL END) > 42.00)
ORDER BY MaximumRate DESC;

For more details description of these example visit the source.

Also visit here and here for some examples with great details.

Insert text into textarea with jQuery

$.fn.extend({
    insertAtCaret: function(myValue) {
        var elemSelected = window.getSelection();
        if(elemSelected) {
            var startPos = elemSelected.getRangeAt(0).startOffset;
            var endPos = elemSelected.getRangeAt(0).endOffset;
            this.val(this.val().substring(0, startPos)+myValue+this.val().substring(endPos,this.val().length));
        } else {
            this.val(this.val()+ myValue) ;
        }
    }
});

How to get time (hour, minute, second) in Swift 3 using NSDate?

let hours = time / 3600
let minutes = (time / 60) % 60
let seconds = time % 60
return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)

"R cannot be resolved to a variable"?

Fix any XML formatting errors in the XML Files in your /res/menu folder.

Might be a compile time error from the XML file being improperly formatted.

How to get selected option using Selenium WebDriver with Java

On the following option:

WebElement option = select.getFirstSelectedOption();
option.getText();

If from the method getText() you get a blank, you can get the string from the value of the option using the method getAttribute:

WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");

How can I add a variable to console.log?

You can use the backslash to include both the story and the players name in one line.

var name=prompt("what is your name?"); console.log("story"\name\"story");

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Maybe It is OpenJPA's bug, When rollback it reset the @Version field, but the pcVersionInit keep true. I have a AbstraceEntity which declared the @Version field. I can workaround it by reset the pcVersionInit field. But It is not a good idea. I think it not work when have cascade persist entity.

    private static Field PC_VERSION_INIT = null;
    static {
        try {
            PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
            PC_VERSION_INIT.setAccessible(true);
        } catch (NoSuchFieldException | SecurityException e) {
        }
    }

    public T call(final EntityManager em) {
                if (PC_VERSION_INIT != null && isDetached(entity)) {
                    try {
                        PC_VERSION_INIT.set(entity, false);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                    }
                }
                em.persist(entity);
                return entity;
            }

            /**
             * @param entity
             * @param detached
             * @return
             */
            private boolean isDetached(final Object entity) {
                if (entity instanceof PersistenceCapable) {
                    PersistenceCapable pc = (PersistenceCapable) entity;
                    if (pc.pcIsDetached() == Boolean.TRUE) {
                        return true;
                    }
                }
                return false;
            }

How to iterate over the files of a certain directory, in Java?

If you have the directory name in myDirectoryPath,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }

Math constant PI value in C

Depending on the library you are using the standard GNU C Predefined Mathematical Constants are here... https://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html

You already have them so why redefine them? Your system desktop calculators probably have them and are even more accurate so you could but just be sure you're not conflicting with existing defined ones to save on compile warnings as they tend to get defaults for things like that. Enjoy!

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

Reading through all these answers, they failed to show the "correct" way of doing it according to Oracle.

Oracle is the only software company I know that heavily relies on custom environment variables. To add %HTTPPORT% to your environment variables, you first need to search for "System Environment Variables" in Windows. There, you should find a button "Change Environment Variables". In the new window, select "New" and type in HTTPPORT as name and 8080 as value. Now, log off and on again, and it magically works!

AES Encrypt and Decrypt

You can use CommonCrypto from iOS or CryptoSwift as external library. There are implementations with both tools below. That said, CommonCrypto output with AES should be tested, as it is not clear in CC documentation, which mode of AES it uses.

CommonCrypto in Swift 4.2

    import CommonCrypto

    func encrypt(data: Data) -> Data {
        return cryptCC(data: data, key: key, operation: kCCEncrypt)
    }

    func decrypt(data: Data) -> Data {
        return cryptCC(data: data, key: key, operation: kCCDecrypt)
    }

    private func cryptCC(data: Data, key: String operation: Int) -> Data {

        guard key.count == kCCKeySizeAES128 else {
            fatalError("Key size failed!")
        }

        var ivBytes: [UInt8]
        var inBytes: [UInt8]
        var outLength: Int

        if operation == kCCEncrypt {
            ivBytes = [UInt8](repeating: 0, count: kCCBlockSizeAES128)
            guard kCCSuccess == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else {
                fatalError("IV creation failed!")
            }

            inBytes = Array(data)
            outLength = data.count + kCCBlockSizeAES128

        } else {
            ivBytes = Array(Array(data).dropLast(data.count - kCCBlockSizeAES128))
            inBytes = Array(Array(data).dropFirst(kCCBlockSizeAES128))
            outLength = inBytes.count

        }

        var outBytes = [UInt8](repeating: 0, count: outLength)
        var bytesMutated = 0

        guard kCCSuccess == CCCrypt(CCOperation(operation), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), Array(key), kCCKeySizeAES128, &ivBytes, &inBytes, inBytes.count, &outBytes, outLength, &bytesMutated) else {
            fatalError("Cryptography operation \(operation) failed")
        }

        var outData = Data(bytes: &outBytes, count: bytesMutated)

        if operation == kCCEncrypt {
            ivBytes.append(contentsOf: Array(outData))
            outData = Data(bytes: ivBytes)
        }
        return outData

    }


CryptoSwift v0.14 in Swift 4.2


    enum Operation {
        case encrypt
        case decrypt
    }

    private let keySizeAES128 = 16
    private let aesBlockSize = 16

    func encrypt(data: Data, key: String) -> Data {
        return crypt(data: data, key: key, operation: .encrypt)
    }

    func decrypt(data: Data, key: String) -> Data {
        return crypt(data: data, key: key, operation: .decrypt)
    }

    private func crypt(data: Data, key: String, operation: Operation) -> Data {

        guard key.count == keySizeAES128 else {
            fatalError("Key size failed!")
        }
        var outData: Data? = nil

        if operation == .encrypt {
            var ivBytes = [UInt8](repeating: 0, count: aesBlockSize)
            guard 0 == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else {
                fatalError("IV creation failed!")
            }

            do {
                let aes = try AES(key: Array(key.data(using: .utf8)!), blockMode: CBC(iv: ivBytes))
                let encrypted = try aes.encrypt(Array(data))
                ivBytes.append(contentsOf: encrypted)
                outData = Data(bytes: ivBytes)

            } catch {
                print("Encryption error: \(error)")
            }

        } else {
            let ivBytes = Array(Array(data).dropLast(data.count - aesBlockSize))
            let inBytes = Array(Array(data).dropFirst(aesBlockSize))

            do {
                let aes = try AES(key: Array(key.data(using: .utf8)!), blockMode: CBC(iv: ivBytes))
                let decrypted = try aes.decrypt(inBytes)
                outData = Data(bytes: decrypted)

            } catch {
                print("Decryption error: \(error)")
            }
        }
        return outData!

    }

Sorting an array in C?

The best sorting technique of all generally depends upon the size of an array. Merge sort can be the best of all as it manages better space and time complexity according to the Big-O algorithm (This suits better for a large array).

How to get MAC address of your machine using a C program?

  1. On Linux, use the service of "Network Manager" over the DBus.

  2. There is also good'ol shell program which can be invoke and the result grabbed (use an exec function under C):

$ /sbin/ifconfig | grep HWaddr

How to set seekbar min and max value

    paySeekRange.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            Debug.i(TAG, "onProgressChanged 1: " + progress);
            int progressMin = (progress * (maxPayRange - minPayRange) / 100) + minPayRange;
            Debug.i(TAG, "onProgressChanged 2: " + progress);
            int progressMax = (progress * (maxPayRange) / 100);
            progress = (progress * (progressMax - progressMin) / 100) + progressMin;
            Debug.i(TAG, "onProgressChanged 3: " + progress);
            txtWeeklyPay.setText("$".concat(String.valueOf(progress)));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

C++: Rounding up to the nearest multiple of a number

well for one thing, since i dont really understand what you want to do, the lines

int roundUp = roundDown + multiple;
int roundCalc = roundUp;
return (roundCalc); 

could definitely be shortened to

int roundUp = roundDown + multiple;
return roundUp;

Undefined index with $_POST

Related question: What is the best way to access unknown array elements without generating PHP notice?

Using the answer from the question above, you can safely get a value from $_POST without generating PHP notice if the key does not exists.

echo _arr($_POST, 'username', 'no username supplied');  
// will print $_POST['username'] or 'no username supplied'

angularjs: ng-src equivalent for background-image:url(...)

Similar to hooblei's answer, just with interpolation:

<li ng-style="{'background-image': 'url({{ image.source }})'}">...</li>

Why use def main()?

"What does if __name__==“__main__”: do?" has already been answered.

Having a main() function allows you to call its functionality if you import the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.

Find and replace string values in list

In case you're wondering about the performance of the different approaches, here are some timings:

In [1]: words = [str(i) for i in range(10000)]

In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop

In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop

In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop

In [5]: import re

In [6]: r = re.compile('1')

In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop

as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:

In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop

In [9]: r = re.compile('(1|324|567)')

In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop

This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.

Laravel Password & Password_Confirmation Validation

Try doing it this way, it worked for me:

$this->validate($request, [
'name' => 'required|min:3|max:50',
'email' => 'email',
'vat_number' => 'max:13',
'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
'password_confirmation' => 'min:6'
]);`

Seems like the rule always has the validation on the first input among the pair...

Android Studio: Unable to start the daemon process

Check your project folder. You may have there a file called gradle.properties and in there, check to see if you don't have this line:

org.gradle.jvmargs=-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

In my case, I just deleted the file, but check the contents to see if you don't actually want to keep some of the settings.

Blurring an image via CSS?

Yes there is using the following code will allow you to apply a blurring effect to the specified image and also it will allow you to choose the amount of blurring.

img {
  -webkit-filter: blur(10px);
    filter: blur(10px);
}

Create folder in Android

Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

File folder = new File(Environment.getExternalStorageDirectory() + 
                             File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
    success = folder.mkdirs();
}
if (success) {
    // Do something on success
} else {
    // Do something else on failure 
}

when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

Do you use the ob_start(ob_gzhandler) function? If so and If you output any content above the ob_start(ob_gzhandler) function, you'll get this error. You can don't use this function or don't output content above this function. The ob_gzhandler callback function will determine what type of content encoding the browser will accept and will return its output accordingly. So if you output content above this function, the content's encoding maybe different from the output content of ob_gzhandler and that cause this error.

AttributeError: 'tuple' object has no attribute

Variables names are only locally meaningful.

Once you hit

return s1,s2,s3,s4

at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.

If you want the variable names to be meaningful after you hit return in the method, you must create an object or dictionary.

How to change value of object which is inside an array using JavaScript or jQuery?

Here is a nice neat clear answer. I wasn't 100% sure this would work but it seems to be fine. Please let me know if a lib is required for this, but I don't think one is. Also if this doesn't work in x browser please let me know. I tried this in Chrome IE11 and Edge they all seemed to work fine.

    var Students = [
        { ID: 1, FName: "Ajay", LName: "Test1", Age: 20},
        { ID: 2, FName: "Jack", LName: "Test2", Age: 21},
        { ID: 3, FName: "John", LName: "Test3", age: 22},
        { ID: 4, FName: "Steve", LName: "Test4", Age: 22}
    ]

    Students.forEach(function (Student) {
        if (Student.LName == 'Test1') {
            Student.LName = 'Smith'
        }
        if (Student.LName == 'Test2') {
            Student.LName = 'Black'
        }
    });

    Students.forEach(function (Student) {
        document.write(Student.FName + " " + Student.LName + "<BR>");
    });

Output should be as follows

Ajay Smith

Jack Black

John Test3

Steve Test4

How do you run a Python script as a service in Windows?

Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).

This is a basic skeleton for a simple service:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        pass

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method

How can I convert tabs to spaces in every file of a directory?

Download and run the following script to recursively convert hard tabs to soft tabs in plain text files.

Execute the script from inside the folder which contains the plain text files.

#!/bin/bash

find . -type f -and -not -path './.git/*' -exec grep -Iq . {} \; -and -print | while read -r file; do {
    echo "Converting... "$file"";
    data=$(expand --initial -t 4 "$file");
    rm "$file";
    echo "$data" > "$file";
}; done;

how to get javaScript event source element?

USE .live()

 $(selector).live(events, data, handler); 

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

$(document).on(events, selector, data, handler);  

Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\"), Server.MapPath("/"). What is the difference?

Just to expand on @splattne's answer a little:

MapPath(string virtualPath) calls the following:

public string MapPath(string virtualPath)
{
    return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}

MapPath(VirtualPath virtualPath) in turn calls MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping) which contains the following:

//...
if (virtualPath == null)
{
    virtualPath = VirtualPath.Create(".");
}
//...

So if you call MapPath(null) or MapPath(""), you are effectively calling MapPath(".")

Run/install/debug Android applications over Wi-Fi?

1- For this I am considering you have already installed the latest version of Android studio. If not you can download it from here.

2 - You can set the platform tools path in environment variable (optional).

3 - Make sure your device and pc connected to same network.

  • plug in the data cable from pc to device.

  • Now, type adb tcpip 5555

  • remove data cable.

  • Then type adb connect 192.168.43.95

  • here 5555 is the port number and 192.168.43.95 is the ip address of the mobile device you can get id address from the mobile settings .

  • Then go to About device and go to status you can see the ip address of the device.

  • You can connect multiple device from different ports which can give ease in development.

  • Or you can go to this link for brief description with screenshots. http://blogssolutions.co.in/connect-your-android-phone-wirelessly-by-adb

Is there a C# String.Format() equivalent in JavaScript?

I created it a long time ago, related question

String.Format = function (b) {
    var a = arguments;
    return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
        if (b.substring(0, 2) == "{{") return b;
        var c = parseInt(b.match(/\d/)[0]);
        return a[c + 1]
    })
};

How to suppress Pandas Future warning ?

@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.


For those who need to know why...

Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all'). With Pandas 0.23.4, you get the following:

>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)

  warnings.warn(d.msg, FutureWarning)

: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

  warnings.warn(d.msg, FutureWarning)

>>>

Following the @bdiamante's advice, you use the warnings library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In fact, disabling all warnings produces the same output:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn on the warning messages shows that the pandas warning system is implemented in core/config_init.py:

$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead

Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!

Correct way to handle conditional styling in React

I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.

Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.

example snippet inside a component:

// if failed, progress bar is red, otherwise green 
<div
    className={`progress-bar ${failed ? failed' : ''}`}
    style={{ width: this.getPercentage() }} 
/>

Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.

So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.

How to pass text in a textbox to JavaScript function?

As opposed to passing the text as a variable, you can use the DOM to retrieve the data in your function:

var text = document.getElementsByName("textbox1").value;

What is the behavior difference between return-path, reply-to and from?

for those who got here because the title of the question:

I use Reply-To: address with webforms. when someone fills out the form, the webpage sends an automatic email to the page's owner. the From: is the automatic mail sender's address, so the owner knows it is from the webform. but the Reply-To: address is the one filled in in the form by the user, so the owner can just hit reply to contact them.

How to use OpenCV SimpleBlobDetector

// creation 
            cv::SimpleBlobDetector * blob_detector; 
            blob_detector = new SimpleBlobDetector(); 
            blob_detector->create("SimpleBlobDetector"); 
// change params - first move it to public!! 
            blob_detector->params.filterByArea = true; 
            blob_detector->params.minArea = 1; 
            blob_detector->params.maxArea = 32000; 
// or read / write them with file 
            FileStorage fs("test_fs.yml", FileStorage::WRITE); 
            FileNode fn = fs["features"]; 

            //blob_detector->read(fn); 
// detect 
            vector<KeyPoint> keypoints; 
            blob_detector->detect(img_text, keypoints); 
            fs.release(); 

I do know why, but params are protected. So I moved it in file features2d.hpp to be public:

  virtual void read( const FileNode& fn ); 
  virtual void write( FileStorage& fs ) const; 

public: 
Params params; 




protected: 
struct CV_EXPORTS Center 
  { 
      Point2d loc 

If you will not do this, the only way to change params is to create file (FileStorage fs("test_fs.yml", FileStorage::WRITE);), than open it in notepad, and edit. Or maybe there is another way, but I`m not aware of it.

How to check if a date is greater than another in Java?

Parse the string into date, then compare using compareTo, before or after

Date d = new Date();
d.compareTo(anotherDate)

i.e

Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(date1string)
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(date2string)

date1.compareTo(date2);

Copying the comment provided below by @MuhammadSaqib to complete this answer.

Returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument, and a value greater than 0 if this Date is after the Date argument. and NullPointerException - if anotherDate is null.

javadoc for compareTo http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo(java.util.Date)

How to write trycatch in R

R uses functions for implementing try-catch block:

The syntax somewhat looks like this:

result = tryCatch({
    expr
}, warning = function(warning_condition) {
    warning-handler-code
}, error = function(error_condition) {
    error-handler-code
}, finally={
    cleanup-code
})

In tryCatch() there are two ‘conditions’ that can be handled: ‘warnings’ and ‘errors’. The important thing to understand when writing each block of code is the state of execution and the scope. @source

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)

This would work, if your are trying to Sum up a list.

Double vs. BigDecimal?

My English is not good so I'll just write a simple example here.

    double a = 0.02;
    double b = 0.03;
    double c = b - a;
    System.out.println(c);

    BigDecimal _a = new BigDecimal("0.02");
    BigDecimal _b = new BigDecimal("0.03");
    BigDecimal _c = _b.subtract(_a);
    System.out.println(_c);

Program output:

0.009999999999999998
0.01

Somebody still want to use double? ;)

Asyncio.gather vs asyncio.wait

A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.


I'll use this example to simulate a coroutine that will raise exceptions, sometimes -

import asyncio
import random


async def a_flaky_tsk(i):
    await asyncio.sleep(i)  # bit of fuzz to simulate a real-world example

    if i % 2 == 0:
        print(i, "ok")
    else:
        print(i, "crashed!")
        raise ValueError

coros = [a_flaky_tsk(i) for i in range(10)]

await asyncio.gather(*coros) outputs -

0 ok
1 crashed!
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
    asyncio.run(main())
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
    await asyncio.gather(*coros)
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

As you can see, the coros after index 1 never got to execute.


But await asyncio.wait(coros) continues to execute tasks, even if some of them fail -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

Ofcourse, this behavior can be changed for both by using -

asyncio.gather(..., return_exceptions=True)

or,

asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)


But it doesn't end here!

Notice: Task exception was never retrieved in the logs above.

asyncio.wait() won't re-raise exceptions from the child tasks until you await them individually. (The stacktrace in the logs are just messages, they cannot be caught!)

done, pending = await asyncio.wait(coros)
for tsk in done:
    try:
        await tsk
    except Exception as e:
        print("I caught:", repr(e))

Output -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()

On the other hand, to catch exceptions with asyncio.gather(), you must -

results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
    if isinstance(result_or_exc, Exception):
        print("I caught:", repr(result_or_exc))

(Same output as before)

Microsoft.ACE.OLEDB.12.0 provider is not registered

I am assuming that if you are running a 64 bit system with a 32 bit database and trying to run a 64 bit console, the following packages need to be installed on the machine.

  1. Install the Microsoft Access Database Engine 2010 x86 Redistributable, this installation is available at: http://www.microsoft.com/download/en/details.aspx?id=13255 .
  2. Data Connectivity Components of Office 2007, this installation is available at: http://www.microsoft.com/download/en/confirmation.aspx?id=23734 .
  3. Microsoft Access Database Engine 2010 x64 Redistributable. You will need to download the package locally and run it with a passive flag. You can download the installation here: http://www.microsoft.com/en-us/download/details.aspx?id=13255 Installing using the command prompt with the '/passive' flag. In the command prompt run the following command: 'AccessDatabaseEngine_x64.exe /passive'

Note: The order seems to matter - so if you have anything installed already, uninstall and follow the steps above.

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

My problem was that I tried to import a Django model before calling django.setup()

This worked for me:

import django
django.setup()

from myapp.models import MyModel

The above script is in the project root folder.

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

I replaced

services.Add(new ServiceDescriptor(typeof(IMyLogger), typeof(MyLogger)));

With

services.AddTransient<IMyLogger, MyLogger>();

And it worked for me.

How can I work with command line on synology?

I use GateOne from the synocommunity.

Go into settings in Package Center and add http://packages.synocommunity.com/ as a package source. Then you should be able to add it easily via Package Center.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In the introduction of Bootstrap it states which imports you need to add. https://getbootstrap.com/docs/4.0/getting-started/introduction/#quick-start

You have to add some scripts in order to get bootstrap fully working. It's important that you include them in this exact order. Popper.js is one of them:

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

I'm hoping you are having the same problem that I had... my issue was simple: Make a fixed textarea with locked percentages inside the container (I'm new to CSS/JS/HTML, so bear with me, if I don't get the lingo correct) so that no matter the device it's displaying on, the box filling the container (the table cell) takes up the correct amount of space. Here's how I solved it:

<table width=100%>
    <tr class="idbbs">
        B.S.:
    </tr></br>
    <tr>
        <textarea id="bsinpt"></textarea>
    </tr>
</table>

Then CSS Looks like this...

#bsinpt
{
    color: gainsboro;
    float: none;
    background: black;
    text-align: left;
    font-family: "Helvetica", "Tahoma", "Verdana", "Arial Black", sans-serif;
    font-size: 100%;
  position: absolute;
  min-height: 60%;
  min-width: 88%;
  max-height: 60%;
  max-width: 88%;
  resize: none;
    border-top-color: lightsteelblue;
    border-top-width: 1px;
    border-left-color: lightsteelblue;
    border-left-width: 1px;
    border-right-color: lightsteelblue;
    border-right-width: 1px;
    border-bottom-color: lightsteelblue;
    border-bottom-width: 1px;
}

Sorry for the sloppy code block here, but I had to show you what's important and I don't know how to insert quoted CSS code on this website. In any case, to ensure you see what I'm talking about, the important CSS is less indented here...

What I then did (as shown here) is very specifically tweak the percentages until I found the ones that worked perfectly to fit display, no matter what device screen is used.

Granted, I think the "resize: none;" is overkill, but better safe than sorry and now the consumers will not have anyway to resize the box, nor will it matter what device they are viewing it from.

It works great.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

If you want to make a change global to the whole notebook:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]

What is Parse/parsing?

From dictionary.reference.com:

Computers. to analyze (a string of characters) in order to associate groups of characters with the syntactic units of the underlying grammar.

The context of the definition is the translation of program text or a language in the general sense into its component parts with respect to a defined grammar -- turning program text into code. In the context of a particular language keyword, though, it generally means to convert the string value of a fundamental data type into an internal representation of that data type. For example, the string "10" becomes the number (integer) 10.

Calling Objective-C method from C++ member function?

Also, you can call into Objective-C runtime to call the method.

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

Sending SMS from PHP

Clickatell is a popular SMS gateway. It works in 200+ countries.

Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

The HTTP/S method is as simple as this:

http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home

You can also test the gateway (incoming and outgoing) for free from your browser

PUT vs. POST in REST

Addition to all answers above:


Most commonly used in professional practice,


  • we use PUT over POST in CREATE operation. Why? because many here said also, responses are not cacheable while POST ones are (Require Content-Location and expiration).
  • We use POST over PUT in UPDATE operation. Why? because it invalidates cached copies of the entire containing resource. which is helpful when updating resources.

Generating a SHA-256 hash from the Linux command line

echo will normally output a newline, which is suppressed with -n. Try this:

echo -n foobar | sha256sum

Add timer to a Windows Forms application

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

Optional Parameters in Go?

Neither optional parameters nor function overloading are supported in Go. Go does support a variable number of parameters: Passing arguments to ... parameters

Very Simple, Very Smooth, JavaScript Marquee

The following works:

http://jsfiddle.net/xAGRJ/4/

The problem with your original code was you are calling scrollticker() by passing a string to setInterval, where you should just pass the function name and treat it as a variable:

lefttime = setInterval(scrollticker, 50);

instead of

lefttime = setInterval("scrollticker()", 50);

Is it possible to simulate key press events programmatically?

just use CustomEvent

Node.prototype.fire=function(type,options){
     var event=new CustomEvent(type);
     for(var p in options){
         event[p]=options[p];
     }
     this.dispatchEvent(event);
}

4 ex want to simulate ctrl+z

window.addEventListener("keyup",function(ev){
     if(ev.ctrlKey && ev.keyCode === 90) console.log(ev); // or do smth
     })

 document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})

How do I encrypt and decrypt a string in python?

Take a look at PyCrypto. It supports Python 3.2 and does exactly what you want.

From their pip website:

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

If you want to encrypt a message of an arbitrary size use AES.MODE_CFB instead of AES.MODE_CBC.

Using JQuery to check if no radio button in a group has been checked

I'm using

$("input:radio[name='html_radio']").is(":checked")

And will return FALSE if all the items in the radiogroup are unchecked and TRUE if an item is checked.

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

Fragment onCreateView and onActivityCreated called twice

The two upvoted answers here show solutions for an Activity with navigation mode NAVIGATION_MODE_TABS, but I had the same issue with a NAVIGATION_MODE_LIST. It caused my Fragments to inexplicably lose their state when the screen orientation changed, which was really annoying. Thankfully, due to their helpful code I managed to figure it out.

Basically, when using a list navigation, ``onNavigationItemSelected()is automatically called when your activity is created/re-created, whether you like it or not. To prevent your Fragment'sonCreateView()from being called twice, this initial automatic call toonNavigationItemSelected()should check whether the Fragment is already in existence inside your Activity. If it is, return immediately, because there is nothing to do; if it isn't, then simply construct the Fragment and add it to the Activity like you normally would. Performing this check prevents your Fragment from needlessly being created again, which is what causesonCreateView()` to be called twice!

See my onNavigationItemSelected() implementation below.

public class MyActivity extends FragmentActivity implements ActionBar.OnNavigationListener
{
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    private boolean mIsUserInitiatedNavItemSelection;

    // ... constructor code, etc.

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
        {
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());

        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id)
    {    
        Fragment fragment;
        switch (position)
        {
            // ... choose and construct fragment here
        }

        // is this the automatic (non-user initiated) call to onNavigationItemSelected()
        // that occurs when the activity is created/re-created?
        if (!mIsUserInitiatedNavItemSelection)
        {
            // all subsequent calls to onNavigationItemSelected() won't be automatic
            mIsUserInitiatedNavItemSelection = true;

            // has the same fragment already replaced the container and assumed its id?
            Fragment existingFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (existingFragment != null && existingFragment.getClass().equals(fragment.getClass()))
            {
                return true; //nothing to do, because the fragment is already there 
            }
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
        return true;
    }
}

I borrowed inspiration for this solution from here.

How to Alter a table for Identity Specification is identity SQL Server

You can't alter the existing columns for identity.

You have 2 options,

Create a new table with identity & drop the existing table

Create a new column with identity & drop the existing column

Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.

CREATE TABLE dbo.Tmp_Names
    (
      Id int NOT NULL
             IDENTITY(1, 1),
      Name varchar(50) NULL
    )
ON  [PRIMARY]
go

SET IDENTITY_INSERT dbo.Tmp_Names ON
go

IF EXISTS ( SELECT  *
            FROM    dbo.Names ) 
    INSERT  INTO dbo.Tmp_Names ( Id, Name )
            SELECT  Id,
                    Name
            FROM    dbo.Names TABLOCKX
go

SET IDENTITY_INSERT dbo.Tmp_Names OFF
go

DROP TABLE dbo.Names
go

Exec sp_rename 'Tmp_Names', 'Names'

Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.

Alter Table Names
Add Id_new Int Identity(1, 1)
Go

Alter Table Names Drop Column ID
Go

Exec sp_rename 'Names.Id_new', 'ID', 'Column'

See the following Microsoft SQL Server Forum post for more details:

http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032

Watermark / hint text / placeholder TextBox

namespace PlaceholderForRichTexxBoxInWPF
{
public MainWindow()
        {
            InitializeComponent();
            Application.Current.MainWindow.WindowState = WindowState.Maximized;// maximize window on load

            richTextBox1.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(rtb_GotKeyboardFocus);
            richTextBox1.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(rtb_LostKeyboardFocus);
            richTextBox1.AppendText("Place Holder");
            richTextBox1.Foreground = Brushes.Gray;
        }
 private void rtb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (sender is RichTextBox)
            {
                TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); 

                if (textRange.Text.Trim().Equals("Place Holder"))
                {
                    ((RichTextBox)sender).Foreground = Brushes.Black;
                    richTextBox1.Document.Blocks.Clear();
                }
            }
        }


        private void rtb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            //Make sure sender is the correct Control.
            if (sender is RichTextBox)
            {
                //If nothing was entered, reset default text.
                TextRange textRange = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); 

                if (textRange.Text.Trim().Equals(""))
                {
                    ((RichTextBox)sender).Foreground = Brushes.Gray;
                    ((RichTextBox)sender).AppendText("Place Holder");
                }
            }
        }
}

File Upload to HTTP server in iphone programming

I thought I would add some server side php code to this answer for any beginners that read this post and are struggling to figure out how to receive the file on the server side and save the file to the filesystem.

I realize that this answer does not directly answer the OP's question, but since Brandon's answer is sufficient for the iOS device side of uploading and he mentions that some knowledge of php is necessary, I thought I would fill in the php gap with this answer.

Here is a class I put together with some sample usage code. Note that the files are stored in directories based on which user is uploading them. This may or may not be applicable to your use, but I thought I'd leave it in place just in case.

<?php


class upload
{
    protected $user;

    protected $isImage;
    protected $isMovie;

    protected $file;
    protected $uploadFilename;
    protected $uploadDirectory;
    protected $fileSize;
    protected $fileTmpName;
    protected $fileType;
    protected $fileExtension;

    protected $saveFilePath;

    protected $allowedExtensions;

function __construct($file, $userPointer)
{
    // set the file we're uploading
    $this->file = $file;

    // if this is tied to a user, link the user account here
    $this->user = $userPointer;

    // set default bool values to false since we don't know what file type is being uploaded yet
    $this->isImage   = FALSE;
    $this->isMovie   = FALSE;

    // setup file properties
    if (isset($this->file) && !empty($this->file))
    {   
        $this->uploadFilename   = $this->file['file']['name'];
        $this->fileSize         = $this->file['file']['size'];
        $this->fileTmpName      = $this->file['file']['tmp_name'];
        $this->fileType         = $this->file['file']['type'];
    }
    else
    {
        throw new Exception('Received empty data. No file found to upload.');
    }

    // get the file extension of the file we're trying to upload
    $tmp = explode('.', $this->uploadFilename);
    $this->fileExtension        = strtolower(end($tmp));

}



public function image($postParams)
{
    // set default error alert (or whatever you want to return if error)
    $retVal = array('alert' => '115');

    // set our bool
    $this->isImage = TRUE;

    // set our type limits
    $this->allowedExtensions    = array("png");

    // setup destination directory path (without filename yet)
    $this->uploadDirectory      = DIR_IMG_UPLOADS.$this->user->uid."/photos/";

    // if user is not subscribed they are allowed only one image, clear their folder here
    if ($this->user->isSubscribed() == FALSE)
    {
        $this->clearFolder($this->uploadDirectory);
    }

    // try to upload the file
    $success = $this->startUpload();

    if ($success === TRUE)
    {
        // return the image name (NOTE: this wipes the error alert set above)
        $retVal = array(
                        'imageName' =>  $this->uploadFilename,
                        );
    }

    return $retVal;
}



public function movie($data)
{
    // update php settings to handle larger uploads
    set_time_limit(300);

    // you may need to increase allowed filesize as well if your server is not set with a high enough limit

    // set default return value (error code for upload failed)
    $retVal = array('alert' => '92');

    // set our bool
    $this->isMovie = TRUE;

    // set our allowed movie types
    $this->allowedExtensions = array("mov", "mp4", "mpv", "3gp");

    // setup destination path
    $this->uploadDirectory = DIR_IMG_UPLOADS.$this->user->uid."/movies/";

    // only upload the movie if the user is a subscriber
    if ($this->user->isSubscribed())
    {
        // try to upload the file
        $success = $this->startUpload();

        if ($success === TRUE)
        {
            // file uploaded so set the new retval
            $retVal = array('movieName' => $this->uploadFilename);
        }
    }
    else
    {
        // return an error code so user knows this is a limited access feature
        $retVal = array('alert' => '13');
    }

    return $retVal;
}




//-------------------------------------------------------------------------------
//                          Upload Process Methods
//-------------------------------------------------------------------------------

private function startUpload()
{
    // see if there are any errors
    $this->checkForUploadErrors();

    // validate the type received is correct
    $this->checkFileExtension();

    // check the filesize
    $this->checkFileSize();

    // create the directory for the user if it does not exist
    $this->createUserDirectoryIfNotExists();

    // generate a local file name
    $this->createLocalFileName();

    // verify that the file is an uploaded file
    $this->verifyIsUploadedFile();

    // save the image to the appropriate folder
    $success = $this->saveFileToDisk();

    // return TRUE/FALSE
    return $success;
}

private function checkForUploadErrors()
{
    if ($this->file['file']['error'] != 0)
    {
        throw new Exception($this->file['file']['error']);
    }
}

private function checkFileExtension()
{
    if ($this->isImage)
    {
        // check if we are in fact uploading a png image, if not return error
        if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'image/png' || exif_imagetype($this->fileTmpName) != IMAGETYPE_PNG)
        {
            throw new Exception('Unsupported image type. The image must be of type png.');
        }
    }
    else if ($this->isMovie)
    {
        // check if we are in fact uploading an accepted movie type
        if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'video/mov')
        {
            throw new Exception('Unsupported movie type. Accepted movie types are .mov, .mp4, .mpv, or .3gp');
        }
    }   
}

private function checkFileSize()
{
    if ($this->isImage)
    {
        if($this->fileSize > TenMB)
        {
            throw new Exception('The image filesize must be under 10MB.');
        }
    }
    else if ($this->isMovie)
    {
        if($this->fileSize > TwentyFiveMB) 
        {
            throw new Exception('The movie filesize must be under 25MB.');
        }
    }
}

private function createUserDirectoryIfNotExists()
{
    if (!file_exists($this->uploadDirectory)) 
    {
        mkdir($this->uploadDirectory, 0755, true);
    }
    else
    {
        if ($this->isMovie)
        {
            // clear any prior uploads from the directory (only one movie file per user)
            $this->clearFolder($this->uploadDirectory);
        }
    }
}

private function createLocalFileName()
{
    $now = time();

    // try to create a unique filename for this users file
    while(file_exists($this->uploadFilename = $now.'-'.$this->uid.'.'.$this->fileExtension))
    {
        $now++;
    }

    // create our full file save path
    $this->saveFilePath = $this->uploadDirectory.$this->uploadFilename;
}

private function clearFolder($path)
{
    if(is_file($path))
    {
        // if there's already a file with this name clear it first
        return @unlink($path);
    }
    elseif(is_dir($path))
    {
        // if it's a directory, clear it's contents
        $scan = glob(rtrim($path,'/').'/*');
        foreach($scan as $index=>$npath)
        {
            $this->clearFolder($npath);
            @rmdir($npath);
        }
    }
}

private function verifyIsUploadedFile()
{
    if (! is_uploaded_file($this->file['file']['tmp_name']))
    {
        throw new Exception('The file failed to upload.');
    }
}


private function saveFileToDisk()
{
    if (move_uploaded_file($this->file['file']['tmp_name'], $this->saveFilePath))
    {
        return TRUE;     
    }

    throw new Exception('File failed to upload. Please retry.');
}

}


?>

Here's some sample code demonstrating how you might use the upload class...

// get a reference to your user object if applicable
$myUser = $this->someMethodThatFetchesUserWithId($myUserId);

// get reference to file to upload
$myFile = isset($_FILES) ? $_FILES : NULL;

// use try catch to return an error for any exceptions thrown in the upload script
try 
{
    // create and setup upload class
    $upload = new upload($myFile, $myUser);

    // trigger file upload
    $data   = $upload->image();     // if uploading an image
    $data  = $upload->movie();      // if uploading movie

    // return any status messages as json string
    echo json_encode($data);
} 
catch (Exception $exception) 
{
    $retData = array(
            'status'    => 'FALSE',
            'payload'   => array(
                            'errorMsg' => $exception->getMessage()
                            ),
                );

    echo json_encode($retData);
}

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

   IEnumerable<Control> Ctrls = from Control ctrl in Me.Controls where ctrl is TextBox | ctrl is GroupBox select ctr;

Lambda Expressions

IEnumerable<Control> Ctrls = Me.Controls.Cast<Control>().Where(c => c is Button | c is GroupBox);

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

Resizing an Image without losing any quality

Are you resizing larger, or smaller? By a small % or by a larger factor like 2x, 3x? What do you mean by quality for your application? And what type of images - photographs, hard-edged line drawings, or what? Writing your own low-level pixel grinding code or trying to do it as much as possible with existing libraries (.net or whatever)?

There is a large body of knowledge on this topic. The key concept is interpolation.

Browsing recommendations:
* http://www.all-in-one.ee/~dersch/interpolator/interpolator.html
* http://www.cambridgeincolour.com/tutorials/image-interpolation.htm
* for C#: https://secure.codeproject.com/KB/GDI-plus/imageprocessing4.aspx?display=PrintAll&fid=3657&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26&select=629945 * this is java-specific but might be educational - http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

creating a random number using MYSQL

Additional to this answer, create a function like

CREATE FUNCTION myrandom(
    pmin INTEGER,
    pmax INTEGER
)
RETURNS INTEGER(11)
DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
  RETURN floor(pmin+RAND()*(pmax-pmin));
END; 

and call like

SELECT myrandom(100,300);

This gives you random number between 100 and 300

Linux command (like cat) to read a specified quantity of characters

head works too:

head -c 100 file  # returns the first 100 bytes in the file

..will extract the first 100 bytes and return them.

What's nice about using head for this is that the syntax for tail matches:

tail -c 100 file  # returns the last 100 bytes in the file

You can combine these to get ranges of bytes. For example, to get the second 100 bytes from a file, read the first 200 with head and use tail to get the last 100:

head -c 200 file | tail -c 100

PowerShell Connect to FTP server and get files

Based on Why does FtpWebRequest download files from the root directory? Can this cause a 553 error?, I wrote a PowerShell script that enabled to download a file from a FTP-Server via explicit FTP over TLS:

# Config
$Username = "USERNAME"
$Password = "PASSWORD"
$LocalFile = "C:\PATH_TO_DIR\FILNAME.EXT"
#e.g. "C:\temp\somefile.txt"
$RemoteFile = "ftp://PATH_TO_REMOTE_FILE"
#e.g. "ftp://ftp.server.com/home/some/path/somefile.txt"

try{ 
    # Create a FTPWebRequest
    $FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
    $FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
    $FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
    $FTPRequest.UseBinary = $true
    $FTPRequest.KeepAlive = $false
    $FTPRequest.EnableSsl  = $true
    # Send the ftp request
    $FTPResponse = $FTPRequest.GetResponse()
    # Get a download stream from the server response
    $ResponseStream = $FTPResponse.GetResponseStream()
    # Create the target file on the local system and the download buffer
    $LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
    [byte[]]$ReadBuffer = New-Object byte[] 1024
    # Loop through the download

    do {
        $ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
        $LocalFileFile.Write($ReadBuffer,0,$ReadLength)
    }
    while ($ReadLength -ne 0)
}catch [Exception]
{
    $Request = $_.Exception
    Write-host "Exception caught: $Request"
}

logger configuration to log to file and print to stdout

Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.

Here's a quick example reusing the assumed values and LOGFILE from the question:

import logging
from logging.handlers import RotatingFileHandler
from logging import handlers
import sys

log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)

fh = handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
fh.setFormatter(format)
log.addHandler(fh)

Dilemma: when to use Fragments vs Activities:

Don't forget that an activity is application's block/component which can be shared and started through Intent! So each activity in your application should solve only one kind of task. If you have only one task in your application then I think you need only one activity and many fragments if needed. Of course you can reuse fragments in future activities which solve another tasks. This approach will be clear and logical separation of tasks. And you no need to maintain one activity with different intent filter parameters for different sets of fragments. You define tasks at the design stage of the development process based on requirements.

How to set a variable to be "Today's" date in Python/Pandas

i got the same problem so tried so many things but finally this is the solution.

import time 

print (time.strftime("%d/%m/%Y"))

How to create roles in ASP.NET Core and assign them to users?

My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.

You could do this easily by creating a CreateRoles method in your startup class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.

private async Task CreateRoles(IServiceProvider serviceProvider)
    {
        //initializing custom roles 
        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        string[] roleNames = { "Admin", "Manager", "Member" };
        IdentityResult roleResult;

        foreach (var roleName in roleNames)
        {
            var roleExist = await RoleManager.RoleExistsAsync(roleName);
            if (!roleExist)
            {
                //create the roles and seed them to the database: Question 1
                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
            }
        }

        //Here you could create a super user who will maintain the web app
        var poweruser = new ApplicationUser
        {

            UserName = Configuration["AppSettings:UserName"],
            Email = Configuration["AppSettings:UserEmail"],
        };
    //Ensure you have these values in your appsettings.json file
        string userPWD = Configuration["AppSettings:UserPassword"];
        var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);

       if(_user == null)
       {
            var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
            if (createPowerUser.Succeeded)
            {
                //here we tie the new user to the role
                await UserManager.AddToRoleAsync(poweruser, "Admin");

            }
       }
    }

and then you could call the CreateRoles(serviceProvider).Wait(); method from the Configure method in the Startup class. ensure you have IServiceProvider as a parameter in the Configure class.

Using role-based authorization in a controller to filter user access: Question 2

You can do this easily, like so.

[Authorize(Roles="Manager")]
public class ManageController : Controller
{
   //....
}

You can also use role-based authorization in the action method like so. Assign multiple roles, if you will

[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
 .....
 */ 
}

While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here

How to check if a Java 8 Stream is empty?

You must perform a terminal operation on the Stream in order for any of the filters to be applied. Therefore you can't know if it will be empty until you consume it.

Best you can do is terminate the Stream with a findAny() terminal operation, which will stop when it finds any element, but if there are none, it will have to iterate over all the input list to find that out.

This would only help you if the input list has many elements, and one of the first few passes the filters, since only a small subset of the list would have to be consumed before you know the Stream is not empty.

Of course you'll still have to create a new Stream in order to produce the output list.

ios app maximum memory budget

I created small utility which tries to allocate as much memory as possible to crash and it records when memory warnings and crash happened. This helps to find out what's the memory budget for any iOS device.

https://github.com/Split82/iOSMemoryBudgetTest

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

You could download Better Touch Tools. It's an app that allows you to make custom key-bindings and shortcuts over your entire system or individual apps. Using it, you could make a shortcut in the terminal that emulates ctrl-a/ctrl-e whenever you press cmd-left/cmd-right, respectively. I definitely recommend it! I've been using it for years and I have over 50 shortcuts spread across several different apps.

Proper way to set response status and JSON content in a REST API made with nodejs and express

You could do it this way:

res.status(400).json(json_response);

This will set the HTTP status code to 400, it works even in express 4.

Save attachments to a folder and rename them

I actually had solved this not long after posting but failed to post my solution. I honestly don't remember it. But, I had to re-visit the task when I was given a new project that faced the same challenge.

I used the ReceivedTime property of Outlook.MailItem to get the time-stamp, I was able to use this as a unique identifier for each file so they do not override one another.

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
        saveFolder = "C:\PathToDirectory\"
    Dim dateFormat As String
        dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Thanks a ton for the other solutions, many of them go above an beyond :)

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

JavaScript load a page on button click

The answers here work to open the page in the same browser window/tab.

However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)

So here is how it worked to open the page in new tab/window:

<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>

It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.

Google.com and clients1.google.com/generate_204

The generate 204 might be dynamically loading the suggestions of search criteria. AS i can see from my load test script, this is seemingly responsible for every server call each time the user types into the text box

How to make a countdown timer in Android?

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

Refer to this link.

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.

fork() child and parent processes

This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
 else 
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

jquery animate background position

jQuery's animate function is not exclusively usable for directly animating properties of DOM-objects. You can also tween variables and use the step function to get the variables for every step of the tween.

For example, to animate a background-position from background-position(0px 0px) to background-position(100px 500px) you can do this:

$({temporary_x: 0, temporary_y: 0}).animate({temporary_x: 100, temporary_y: 500}, {
    duration: 1000,
    step: function() {
        var position = Math.round(this.temporary_x) + "px " + Math.round(this.temporary_y) + "px";
        $("#your_div").css("background-position",  position);
    }
});

Just make sure to not forget the this. inside the step function.

Tree implementation in Java (root, parents and children)

The process of assembling tree nodes is similar to the process of assembling lists. We have a constructor for tree nodes that initializes the instance variables.

public Tree (Object cargo, Tree left, Tree right) { 
    this.cargo = cargo; 
    this.left = left; 
    this.right = right; 
} 

We allocate the child nodes first:

Tree left = new Tree (new Integer(2), null, null); 
Tree right = new Tree (new Integer(3), null, null); 

We can create the parent node and link it to the children at the same time:

Tree tree = new Tree (new Integer(1), left, right); 

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

My problem was solved that way:

Your username is probably restricted, You must grant full access to the user.

  1. Right Click on Project and select Properties
  2. Click on Tab Security
  3. Click Edit button
  4. Found Current User and Permission for User Allow Full Control

When to use window.opener / window.parent / window.top

top, parent, opener (as well as window, self, and iframe) are all window objects.

  1. window.opener -> returns the window that opens or launches the current popup window.
  2. window.top -> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.
  3. window.parent -> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or self

CSV new-line character seen in unquoted field error

This is an error that I faced. I had saved .csv file in MAC OSX.

While saving, save it as "Windows Comma Separated Values (.csv)" which resolved the issue.

Single vs Double quotes (' vs ")

Using double quotes for HTML

i.e.

<div class="colorFont"></div>

Using single quotes for JavaScript

i.e.

$('#container').addClass('colorFont');
$('<div class="colorFont2></div>');

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

I figured that the DJANGO_SETTINGS_MODULE had to be set some way, so I looked at the documentation (link updated) and found:

export DJANGO_SETTINGS_MODULE=mysite.settings

Though that is not enough if you are running a server on heroku, you need to specify it there, too. Like this:

heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <your account name> 

In my specific case I ran these two and everything worked out:

export DJANGO_SETTINGS_MODULE=nirla.settings
heroku config:set DJANGO_SETTINGS_MODULE=nirla.settings --account personal

Edit

I would also like to point out that you have to re-do this every time you close or restart your virtual environment. Instead, you should automate the process by going to venv/bin/activate and adding the line: set DJANGO_SETTINGS_MODULE=mysite.settings to the bottom of the code. From now on every time you activate the virtual environment, you will be using that app's settings.

Represent space and tab in XML tag

New, expanded answer to an old, commonly asked question...

Whitespace in XML Component Names

Summary: Whitespace characters are not permitted in XML element or attribute names.

Here are the main Unicode code points related to whitespace:

  • #x0009 CHARACTER TABULATION
  • #x0020 SPACE
  • #x000A LINE FEED (LF)
  • #x000D CARRIAGE RETURN (CR)
  • #x00A0 NO-BREAK SPACE
  • [#x2002-#x200A] EN SPACE through HAIR SPACE
  • #x205F MEDIUM MATHEMATICAL SPACE
  • #x3000 IDEOGRAPHIC SPACE

None of these code points are permitted by the W3C XML BNF for XML names:

NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] |
                  [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] |
                  [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] |
                  [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
                  [#x10000-#xEFFFF]
NameChar      ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] |
                  [#x203F-#x2040]
Name          ::= NameStartChar (NameChar)*

Whitespace in XML Content (Not Component Names)

Summary: Whitespace characters are, of course, permitted in XML content.

All of the above whitespace codepoints are permitted in XML content by the W3C XML BNF for Char:

Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
/* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */

Unicode code points can be inserted as character references. Both decimal &#decimal; and hexadecimal &#xhex; forms are supported.

Pad with leading zeros

You can do this with a string datatype. Use the PadLeft method:

var myString = "1";
myString = myString.PadLeft(myString.Length + 5, '0');

000001

How to convert a column of DataTable to a List

Here you go.

           DataTable defaultDataTable = defaultDataSet.Tables[0];
           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>("column1") == something
                    select x.Field<string>("column2")).ToList();

If you need the first column

           var list = (from x in defaultDataTable.AsEnumerable()
                    where x.Field<string>(1) == something
                    select x.Field<string>(1)).ToList();

If else on WHERE clause

try this ,hope it helps

select user_display_image as user_image,
user_display_name as user_name,
invitee_phone,
(
 CASE 
    WHEN invitee_status=1 THEN "attending" 
    WHEN invitee_status=2 THEN "unsure" 
    WHEN invitee_status=3 THEN "declined" 
    WHEN invitee_status=0 THEN "notreviwed" END
) AS  invitee_status
 FROM your_tbl

How can I detect when an Android application is running in the emulator?

Don't know if there are better ways to detect the emu, but the emulator will have the file init.goldfish.rc in the root-directory.

It's the emulator specific startup-script, and it shouldn't be there on a non-emulator build.

How to set Angular 4 background image?

Below answer worked for angular 4/5.

In app.component.css

.image{
     height:40em; background-size:cover; width:auto;
     background-image:url('copied image address');
     background-position:50% 50%;
   }

Also in app.component.html simply add as below

<div class="image">
Your content
</div>

This way I was able to set background image in Angular 4/5.

Strip HTML from strings in Python

Using BeautifulSoup, html2text or the code from @Eloff, most of the time, it remains some html elements, javascript code...

So you can use a combination of these libraries and delete markdown formatting (Python 3):

import re
import html2text
from bs4 import BeautifulSoup
def html2Text(html):
    def removeMarkdown(text):
        for current in ["^[ #*]{2,30}", "^[ ]{0,30}\d\\\.", "^[ ]{0,30}\d\."]:
            markdown = re.compile(current, flags=re.MULTILINE)
            text = markdown.sub(" ", text)
        return text
    def removeAngular(text):
        angular = re.compile("[{][|].{2,40}[|][}]|[{][*].{2,40}[*][}]|[{][{].{2,40}[}][}]|\[\[.{2,40}\]\]")
        text = angular.sub(" ", text)
        return text
    h = html2text.HTML2Text()
    h.images_to_alt = True
    h.ignore_links = True
    h.ignore_emphasis = False
    h.skip_internal_links = True
    text = h.handle(html)
    soup = BeautifulSoup(text, "html.parser")
    text = soup.text
    text = removeAngular(text)
    text = removeMarkdown(text)
    return text

It works well for me but it can be enhanced, of course...

Hiding a password in a python script (insecure obfuscation only)

How about importing the username and password from a file external to the script? That way even if someone got hold of the script, they wouldn't automatically get the password.

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

Difference between core and processor

I have read all answers, but this link was more clear explanation for me about difference between CPU(Processor) and Core. So I'm leaving here some notes from there.

The main difference between CPU and Core is that the CPU is an electronic circuit inside the computer that carries out instruction to perform arithmetic, logical, control and input/output operations while the core is an execution unit inside the CPU that receives and executes instructions.

enter image description here

Accessing dict keys like an attribute?

This is what I use

args = {
        'batch_size': 32,
        'workers': 4,
        'train_dir': 'train',
        'val_dir': 'val',
        'lr': 1e-3,
        'momentum': 0.9,
        'weight_decay': 1e-4
    }
args = namedtuple('Args', ' '.join(list(args.keys())))(**args)

print (args.lr)

Error message "No exports were found that match the constraint contract name"

Deleting the folders haven't worked for me i have go control panel and repaired

Visual Studio Installer Projects extensions for VS 2013.

And it worked for me

AttributeError: 'module' object has no attribute 'urlopen'

This works in Python 2.x.

For Python 3 look in the docs:

import urllib.request

with urllib.request.urlopen("http://www.python.org") as url:
    s = url.read()
    # I'm guessing this would output the html source code ?
    print(s)

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

Where do I find the current C or C++ standard documents?

Online versions of the standard can be found:

Working Draft, Standard for Programming Language C++

The following all draft versions of the standard:
All the following are freely downloadable
(many of these can be found at this main GitHub link)
2020-10-18: N4868 git
2020-04-08: N4861 git
2020-01-14: N4849 git
2019-11-27: N4842 git
2019-10-08: N4835 git
2019-08-15: N4830 git
2019-06-17: N4820 git
2019-03-15: N4810 git
2019-01-21: N4800 git
2018-11-26: N4791 git
2018-10-08: N4778 git
2018-07-07: N4762 git
2018-05-07: N4750 git
2018-04-02: N4741 git
2018-02-12: N4727 git
2017-11-27: N4713 git
2017-10-16: N4700 git
2017-07-30: N4687 git

This seems to be the new standard:
These version requires Authentication
2017-03-21: N4660 is the C++17 Draft Standard

The following all draft versions of the standard:
All the following are freely downloadable
2017-03-21: N4659 git
2017-02-06: N4640 git
2016-11-28: N4618 git
2016-07-12: N4606 git
2016-05-30: N4594 git
2016-03-19: N4582 git
2015-11-09: N4567 git
2015-05-22: N4527 git
2015-04-10: N4431 git
2014-11-19: N4296 git

This seems to be the old C++14 standard:
These version requires Authentication
2014-10-07: N4140 git Essentially C++14 with minor errors and typos corrected
2014-09-02: N4141 git Standard C++14
2014-03-02: N3937
2014-03-02: N3936 git

The following all draft versions of the standard:
All the following are freely downloadable
2013-10-13: N3797 git
2013-05-16: N3691
2013-05-15: N3690
2012-11-02: N3485
2012-02-28: N3376
2012-01-16: N3337 git Essentially C++11 with minor errors and typos corrected

This seems to be the old C++11 standard:
This version requires Authentication
2011-04-05: N3291 C++11 (Or Very Close)

The following all draft versions of the standard:
All the following are freely downloadable
2011-02-28: N3242 (differences from N3291 very minor)
2010-11-27: N3225
2010-08-21: N3126
2010-03-29: N3090
2010-02-16: N3035
2009-11-09: N3000
2009-09-25: N2960
2009-06-22: N2914
2009-03-23: N2857
2008-10-04: N2798
2008-08-25: N2723
2008-06-27: N2691
2008-05-19: N2606
2008-03-17: N2588
2008-02-04: N2521
2007-10-22: N2461
2007-08-06: N2369
2007-06-25: N2315
2007-05-07: N2284
2006-11-03: N2134
2006-04-21: N2009
2005-10-19: N1905
2005-04-27: N1804

This seems to be the old C++03 standard:
All the below versions require Authentication
2004-11-05: N1733
2004-07-16: N1655 Unofficial
2004-02-07: N1577 C++03 (Or Very Close)
2001-09-13: N1316 Draft Expanded Technical Corrigendum
1997-00-00: N1117 Draft Expanded Technical Corrigendum

The following all draft versions of the standard:
All the following are freely downloadable
1996-00-00: N0836 Draft Expanded Technical Corrigendum
1995-00-00: N0785 Working Paper for Draft Proposed International Standard for Information Systems - Programming Language C++

Other Interesting Papers:

2020 / 2019 / 2018 / 2017 / 2016 / 2015 / 2014 / 2013 / 2012 / 2011

Creating your own header file in C

myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

How can I know if a branch has been already merged into master?

You can use the git merge-base command to find the latest common commit between the two branches. If that commit is the same as your branch head, then the branch has been completely merged.

Note that git branch -d does this sort of thing already because it will refuse to delete a branch that hasn't already been completely merged.

HTTPS connections over proxy servers

tunneling HTTPS through SSH (linux version):

1) turn off using 443 on localhost
2) start tunneling as root: ssh -N login@proxy_server -L 443:target_ip:443
3) adding 127.0.0.1 target_domain.com to /etc/hosts

everything you do on localhost. then:

target_domain.com is accessible from localhost browser.

Get name of currently executing test in JUnit 4

Consider using SLF4J (Simple Logging Facade for Java) provides some neat improvements using parameterized messages. Combining SLF4J with JUnit 4 rule implementations can provide more efficient test class logging techniques.

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.rules.TestWatchman;
import org.junit.runners.model.FrameworkMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingTest {

  @Rule public MethodRule watchman = new TestWatchman() {
    public void starting(FrameworkMethod method) {
      logger.info("{} being run...", method.getName());
    }
  };

  final Logger logger =
    LoggerFactory.getLogger(LoggingTest.class);

  @Test
  public void testA() {

  }

  @Test
  public void testB() {

  }
}

How can I display a modal dialog in Redux that performs asynchronous actions?

A lot of good solutions and valuable commentaries by known experts from JS community on the topic could be found here. It could be an indicator that it's not that trivial problem as it may seem. I think this is why it could be the source of doubts and uncertainty on the issue.

Fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?

I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale

Rationale

react/react-dom comes comes with 2 basic assumptions/ideas:

  • every UI is hierarchical naturally. This why we have the idea of components which wrap each other
  • react-dom mounts (physically) child component to its parent DOM node by default

The problem is that sometimes the second property isn't what you want in your case. Sometimes you want to mount your component into different physical DOM node and hold logical connection between parent and child at the same time.

Canonical example is Tooltip-like component: at some point of development process you could find that you need to add some description for your UI element: it'll render in fixed layer and should know its coordinates (which are that UI element coord or mouse coords) and at the same time it needs information whether it needs to be shown right now or not, its content and some context from parent components. This example shows that sometimes logical hierarchy isn't match with the physical DOM hierarchy.

Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question:

import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
  const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
  return (
    <Cell {...props}>
        // the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
        <Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
            hideMe, // alias for `hide(modalId)`
            index } // useful to know to set zIndex, for example
            , e) => // access to the arguments (click event data in this example)
          <Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
            <ConfirmationDialog
              title={ 'Delete' }
              message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
              confirmButton={ <Button type="primary">DELETE</Button> }
              onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
              close={ hideMe } />
          </Modal> }
        </Layer>

        // this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
        <LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
          <div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
            <Icon type="trash" />
          </div> }
        </LayerContext>
    </Cell>)
// ...

How can I pass data from Flask to JavaScript in a template?

Using a data attribute on an HTML element avoids having to use inline scripting, which in turn means you can use stricter CSP rules for increased security.

Specify a data attribute like so:

<div id="mydiv" data-geocode='{{ geocode|tojson }}'>...</div>

Then access it in a static JavaScript file like so:

// Raw JavaScript
var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode);

// jQuery
var geocode = JSON.parse($("#mydiv").data("geocode"));

Calculating sum of repeated elements in AngularJS ng-repeat

You can use a custom Angular filter that takes the dataset object array and the key in each object to sum. The filter can then return the sum:

.filter('sumColumn', function(){
        return function(dataSet, columnToSum){
            let sum = 0;

            for(let i = 0; i < dataSet.length; i++){
                sum += parseFloat(dataSet[i][columnToSum]) || 0;
            }

            return sum;
        };
    })

Then in your table to sum a column you can use:

<th>{{ dataSet | sumColumn: 'keyInObjectToSum' }}</th>

What are the best use cases for Akka framework

If you abstract the chat server up a level, then you get the answer.

Akka provides a messaging system that is akin to Erlang's "let it crash" mentality.

So examples are things that need varying levels of durability and reliability of messaging:

  • Chat server
  • Network layer for an MMO
  • Financial data pump
  • Notification system for an iPhone/mobile/whatever app
  • REST Server
  • Maybe something akin to WebMachine (guess)

The nice things about Akka are the choices it affords for persistence, it's STM implementation, REST server and fault-tolerance.

Don't get annoyed by the example of a chat server, think of it as an example of a certain class of solution.

With all their excellent documentation, I feel like a gap is this exact question, use-cases and examples. Keeping in mind the examples are non-trivial.

(Written with only experience of watching videos and playing with the source, I have implemented nothing using akka.)

White space at top of page

overflow: auto

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

Create timestamp variable in bash script

ISO 8601 format (2018-12-23T12:34:56) is more readable than UNIX timestamp. However on some OSs you cannot have : in the filenames. Therefore I recommend using something like this instead:

2018-12-23_12-34-56

You can use the following command to get the timestamp in this format:

TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`

This is the format I have seen many applications use. Another nice thing about this is that if your file names start with this, you can sort them alphabetically and they would be sorted by date.

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Daniel answer is right on the spot. If you want to query more than one field do this:

Employee.objects.values_list('eng_name','rank')

This will return list of tuples. You cannot use named=Ture when querying more than one field.

Moreover if you know that only one field exists with that info and you know the pk id then do this:

Employee.objects.values_list('eng_name','rank').get(pk=1)

Function or sub to add new row and data to table

This should help you.

Dim Ws As Worksheet
Set Ws = Sheets("Sheet-Name")
Dim tbl As ListObject
Set tbl = Ws.ListObjects("Table-Name")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add

With newrow

        .Range(1, Ws.Range("Table-Name[Table-Column-Name]").Column) = "Your Data"

End With

firefox proxy settings via command line

it working perfect.

cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
echo user_pref("network.proxy.ftp", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.ftp_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.http", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.http_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.share_proxy_settings", true); >>prefs.js
echo user_pref("network.proxy.socks", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.socks_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.ssl", "YOUR_PROXY_SERVER"); >>prefs.js
echo user_pref("network.proxy.ssl_port", YOUR_PROXY_PORT); >>prefs.js
echo user_pref("network.proxy.type", 1); >>prefs.js
set ffile=
cd %windir%

How to get the current directory in a C program?

Use getcwd

#include <stdio.h>  /* defines FILENAME_MAX */
//#define WINDOWS  /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

int main(){
  char buff[FILENAME_MAX];
  GetCurrentDir( buff, FILENAME_MAX );
  printf("Current working dir: %s\n", buff);
  return 1;
}

OR

#include<stdio.h>
#include<unistd.h> 
#include<stdlib.h>

main() {
char *buf;
buf=(char *)malloc(100*sizeof(char));
getcwd(buf,100);
printf("\n %s \n",buf);
}

NoSql vs Relational database

NOSQL has no special advantages over the relational database model. NOSQL does address certain limitations of current SQL DBMSs but it doesn't imply any fundamentally new capabilities over previous data models.

NOSQL means only no SQL (or "not only SQL") but that doesn't mean the same as no relational. A relational database in principle would make a very good NOSQL solution - it's just that none of the current set of NOSQL products uses the relational model.

How to use Fiddler to monitor WCF service

You can use the Free version of HTTP Debugger.

It is not a proxy and you needn't make any changes in web.config.

Also, it can show both; incoming and outgoing HTTP requests. HTTP Debugger Free

cor shows only NA or 1 for correlations - Why?

The 1s are because everything is perfectly correlated with itself, and the NAs are because there are NAs in your variables.

You will have to specify how you want R to compute the correlation when there are missing values, because the default is to only compute a coefficient with complete information.

You can change this behavior with the use argument to cor, see ?cor for details.

Python: Get the first character of the first string in a list?

Try mylist[0][0]. This should return the first character.

Read file line by line in PowerShell

I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.

[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
    $line = $sr.ReadLine()
}
$sr.Close() 

XML Carriage return encoding

To insert a CR into XML, you need to use its character entity &#13;.

This is because compliant XML parsers must, before parsing, translate CRLF and any CR not followed by a LF to a single LF. This behavior is defined in the End-of-Line handling section of the XML 1.0 specification.

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

As everyone here said, that's not possible directly.

The method I prefer and is rather clean, is to use an Object Mapper like AutoMapper.

It will do the task of copying properties from one instance to another (Not necessarily the same type) automatically.

What Language is Used To Develop Using Unity

One can use any one of the following three scripting languages:

  1. JavaScript
  2. C#
  3. Boo

But my personal choice is C# because I find it faster in comparison to other two.

How do I change select2 box height

Quick and easy, add this to your page:

<style>
    .select2-results {
        max-height: 500px;
    }
</style>

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

What is the string concatenation operator in Oracle?

There's also concat, but it doesn't get used much

select concat('a','b') from dual;

Using global variables in a function

You need to reference the global variable in every function you want to use.

As follows:

var = "test"

def printGlobalText():
    global var #wWe are telling to explicitly use the global version
    var = "global from printGlobalText fun."
    print "var from printGlobalText: " + var

def printLocalText():
    #We are NOT telling to explicitly use the global version, so we are creating a local variable
    var = "local version from printLocalText fun"
    print "var from printLocalText: " + var

printGlobalText()
printLocalText()
"""
Output Result:
var from printGlobalText: global from printGlobalText fun.
var from printLocalText: local version from printLocalText
[Finished in 0.1s]
"""

LINQ query on a DataTable

var results = from myRow in myDataTable
where results.Field<Int32>("RowNo") == 1
select results;

Java 8 - Best way to transform a list: map or foreach?

If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write

ListX myListToParse;

ListX myFinalList = myListToParse.filter(elt -> elt != null) .map(elt -> doSomething(elt));

myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).

[Disclosure I am the lead developer of cyclops-react]

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I noticed I had accidentally deleted var window:UIWindow? line from AppDelegate. Introducing it again fixed the issue for me!

grep a file, but show several surrounding lines?

Here is the @Ygor solution in awk

awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s="pattern" myfile

Note: Replace a and b variables with number of lines before and after.

It's especially useful for system which doesn't support grep's -A, -B and -C parameters.

Click toggle with jQuery

try changing this:

$(this).find(':checkbox').attr('checked', true ); 

to this:

$(this).find(':checkbox').attr('checked', 'checked'); 

Not 100% sure if that will do it, but I seem to recall having a similar problem. Good luck!

Maven Jacoco Configuration - Exclude classes/packages from report not working

Another solution:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.5.201505241946</version>
    <executions>
        <execution>
            <id>default-prepare-agent</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>default-report</id>
            <phase>prepare-package</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>default-check</id>
            <goals>
                <goal>check</goal>
            </goals>
            <configuration>
                <rules>
                    <rule implementation="org.jacoco.maven.RuleConfiguration">
                        <excludes>
                            <exclude>com.mypackage1</exclude
                            <exclude>com.mypackage2</exclude>
                        </excludes>
                        <element>PACKAGE</element>
                        <limits>
                            <limit implementation="org.jacoco.report.check.Limit">
                                <counter>COMPLEXITY</counter>
                                <value>COVEREDRATIO</value>
                                <minimum>0.85</minimum>
                            </limit>
                        </limits>
                    </rule>
                </rules>
            </configuration>
        </execution>
    </executions>
</plugin>

Please note that, we are using "<element>PACKAGE</element>" in the configuration which then helps us to exclude at package level.

How do you run a command for each line of a file?

If you want to run your command in parallel for each line you can use GNU Parallel

parallel -a <your file> <program>

Each line of your file will be passed to program as an argument. By default parallel runs as many threads as your CPUs count. But you can specify it with -j

Display / print all rows of a tibble (tbl_df)

The tibble vignette has an updated way to change its default printing behavior:

You can control the default appearance with options:

options(tibble.print_max = n, tibble.print_min = m): if there are more than n rows, print only the first m rows. Use options(tibble.print_max = Inf) to always show all rows.

options(tibble.width = Inf) will always print all columns, regardless of the width of the screen.

examples

This will always print all rows:

options(tibble.print_max = Inf)

This will not actually limit the printing to 50 lines:

options(tibble.print_max = 50)

But this will restrict printing to 50 lines:

options(tibble.print_max = 50, tibble.print_min = 50)

How to make EditText not editable through XML in Android?

I tried to do:

textView.setInputType( InputType.TYPE_NULL );

which should work, but for me it did not.

I finished with this code:

textView.setKeyListener(new NumberKeyListener() {
    public int getInputType() {
        return InputType.TYPE_NULL;
    }

    protected char[] getAcceptedChars() {
        return new char[] {};
    }
});

which works perfectly.

What is the difference between Document style and RPC style communication?

I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.

Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.

Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.

In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.

I would suggest using Document Wrapped as the web service type of choice due to its advantages.

SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.

If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.

A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services

What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

Well, var x = new Array() is different than var x = [] is different in some features I'll just explain the most useful two (in my opinion) of them.

Before I get into expalining the differences, I will set a base first; when we use x = [] defines a new variable with data type of Array, and it inherits all the methods that belong to the array prototype, something pretty similar (but not exactly) to extending a class. However, when we use x = new Array() it initilizes a clone of the array prototype assigned to the variable x.

Now let's see what are the difference

The First Difference is that using new Array(x) where x is an integer, initilizes an array of x undefined values, for example new Array(16) will initialize an array with 16 items all of them are undefined. This is very useful when you asynchronously fill an array of a predefined length. For example (again :) ) let's say you are getting the results of 100 competitiors, and you're receiving them asynchronously from a remote system or db, then you'll need to allocate them in the array according to the rank once you receive each result. In this very rare case you will do something like myArray[result.rank - 1] = result.name, so the rank 1 will be set to the index 0 and so on.

The second difference is that using new Array() as you already know, instanciates a whole new clone of the array prototype and assigns it to your variable, that allows you to do some magic (not recommended btw). This magic is that you can overwrite a specific method of the legacy array methods. So, for example you can set the Array.push method to push the new value to the beginning of the array instead of the end, and you can also add new methods (this is better) to this specific clone of the Array Prototype. That will allow you to define more complex types of arrays throughout your project with your own added methods and use it as a class.

Last thing, if you're from the very few people (that I truly love) that care about processing overhead and memory consumption of your app, you'd never tough new Array() without being desperate to use it :).

I hope that has explained enough about the beast new Array() :)

How can I unstage my files again after making a local commit?

git reset --soft is just for that: it is like git reset --hard, but doesn't touch the files.