Programs & Examples On #Multiple login

How to convert Milliseconds to "X mins, x seconds" in Java?

I would not pull in the extra dependency just for that (division is not that hard, after all), but if you are using Commons Lang anyway, there are the DurationFormatUtils.

Example Usage (adapted from here):

import org.apache.commons.lang3.time.DurationFormatUtils

public String getAge(long value) {
    long currentTime = System.currentTimeMillis();
    long age = currentTime - value;
    String ageString = DurationFormatUtils.formatDuration(age, "d") + "d";
    if ("0d".equals(ageString)) {
        ageString = DurationFormatUtils.formatDuration(age, "H") + "h";
        if ("0h".equals(ageString)) {
            ageString = DurationFormatUtils.formatDuration(age, "m") + "m";
            if ("0m".equals(ageString)) {
                ageString = DurationFormatUtils.formatDuration(age, "s") + "s";
                if ("0s".equals(ageString)) {
                    ageString = age + "ms";
                }
            }
        }
    }
    return ageString;
}   

Example:

long lastTime = System.currentTimeMillis() - 2000;
System.out.println("Elapsed time: " + getAge(lastTime)); 

//Output: 2s

Note: To get millis from two LocalDateTime objects you can use:

long age = ChronoUnit.MILLIS.between(initTime, LocalDateTime.now())

How to align an image dead center with bootstrap

I need the same and here I found the solution:

https://stackoverflow.com/a/15084576/1140407

<div class="container">
  <div class="row">
    <div class="span9 centred">
      This div will be centred.
    </div>
  </div>
</div>

and to CSS:

[class*="span"].centred {
  margin-left: auto;
  margin-right: auto;
  float: none;
}

Eclipse JPA Project Change Event Handler (waiting)

Don't know why, my Neon Eclipse still having this issue, it doesn't seem to be fixed in Mars version as many people said.

I found that using command is too troublesome, I delete the plugin away via the Eclipse Installation Manager.

Neon: [Help > Installation Details > Installed Software]

Oxygen: [Preferences > Install/Update > Installed Software]

Just select the plugin "Dali Java Persistence Tools -JPA Support" and click "uninstall" will do. Please take note my screen below doesn't have that because I already uninstalled.

enter image description here

How can foreign key constraints be temporarily disabled using T-SQL?

Find the constraint

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')

Execute the SQL generated by this SQL

SELECT 
    'ALTER TABLE ' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '.[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')

Safeway.

Note: Added solution for droping the constraint so that table can be dropped or modified without any constraint error.

How can I tell if a DOM element is visible in the current viewport?

As a public service:
Dan's answer with the correct calculations (element can be > window, especially on mobile phone screens), and correct jQuery testing, as well as adding isElementPartiallyInViewport:

By the way, the difference between window.innerWidth and document.documentElement.clientWidth is that clientWidth/clientHeight doesn't include the scrollbar, while window.innerWidth/Height does.

function isElementPartiallyInViewport(el)
{
    // Special bonus for those using jQuery
    if (typeof jQuery !== 'undefined' && el instanceof jQuery) 
        el = el[0];

    var rect = el.getBoundingClientRect();
    // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }
    var windowHeight = (window.innerHeight || document.documentElement.clientHeight);
    var windowWidth = (window.innerWidth || document.documentElement.clientWidth);

    // http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
    var vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);
    var horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);

    return (vertInView && horInView);
}


// http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
function isElementInViewport (el)
{
    // Special bonus for those using jQuery
    if (typeof jQuery !== 'undefined' && el instanceof jQuery) 
        el = el[0];

    var rect = el.getBoundingClientRect();
    var windowHeight = (window.innerHeight || document.documentElement.clientHeight);
    var windowWidth = (window.innerWidth || document.documentElement.clientWidth);

    return (
           (rect.left >= 0)
        && (rect.top >= 0)
        && ((rect.left + rect.width) <= windowWidth)
        && ((rect.top + rect.height) <= windowHeight)
    );
}


function fnIsVis(ele)
{
    var inVpFull = isElementInViewport(ele);
    var inVpPartial = isElementPartiallyInViewport(ele);
    console.clear();
    console.log("Fully in viewport: " + inVpFull);
    console.log("Partially in viewport: " + inVpPartial);
}

Test-case

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Test</title>
    <!--
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="scrollMonitor.js"></script>
    -->

    <script type="text/javascript">

        function isElementPartiallyInViewport(el)
        {
            // Special bonus for those using jQuery
            if (typeof jQuery !== 'undefined' && el instanceof jQuery) 
                el = el[0];

            var rect = el.getBoundingClientRect();
            // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }
            var windowHeight = (window.innerHeight || document.documentElement.clientHeight);
            var windowWidth = (window.innerWidth || document.documentElement.clientWidth);

            // http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
            var vertInView = (rect.top <= windowHeight) && ((rect.top + rect.height) >= 0);
            var horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);

            return (vertInView && horInView);
        }


        // http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
        function isElementInViewport (el)
        {
            // Special bonus for those using jQuery
            if (typeof jQuery !== 'undefined' && el instanceof jQuery) 
                el = el[0];

            var rect = el.getBoundingClientRect();
            var windowHeight = (window.innerHeight || document.documentElement.clientHeight);
            var windowWidth = (window.innerWidth || document.documentElement.clientWidth);

            return (
                   (rect.left >= 0)
                && (rect.top >= 0)
                && ((rect.left + rect.width) <= windowWidth)
                && ((rect.top + rect.height) <= windowHeight)
            );
        }


        function fnIsVis(ele)
        {
            var inVpFull = isElementInViewport(ele);
            var inVpPartial = isElementPartiallyInViewport(ele);
            console.clear();
            console.log("Fully in viewport: " + inVpFull);
            console.log("Partially in viewport: " + inVpPartial);
        }


        // var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft,
        // var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    </script>
</head>

<body>
    <div style="display: block; width: 2000px; height: 10000px; background-color: green;">

        <br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br /><br />

        <input type="button" onclick="fnIsVis(document.getElementById('myele'));" value="det" />

        <br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br /><br />

        <div style="background-color: crimson; display: inline-block; width: 800px; height: 500px;" ></div>
        <div id="myele" onclick="fnIsVis(this);" style="display: inline-block; width: 100px; height: 100px; background-color: hotpink;">
        t
        </div>

        <br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br /><br />
        <br /><br /><br /><br /><br /><br />

        <input type="button" onclick="fnIsVis(document.getElementById('myele'));" value="det" />
    </div>

    <!--
    <script type="text/javascript">

        var element = document.getElementById("myele");
        var watcher = scrollMonitor.create(element);

        watcher.lock();

        watcher.stateChange(function() {
            console.log("state changed");
            // $(element).toggleClass('fixed', this.isAboveViewport)
        });
    </script>
    -->
</body>
</html>

How to create separate AngularJS controller files?

What about this solution? Modules and Controllers in Files (at the end of the page) It works with multiple controllers, directives and so on:

app.js

var app = angular.module("myApp", ['deps']);

myCtrl.js

app.controller("myCtrl", function($scope) { ..});

html

<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

Google has also a Best Practice Recommendations for Angular App Structure I really like to group by context. Not all the html in one folder, but for example all files for login (html, css, app.js,controller.js and so on). So if I work on a module, all the directives are easier to find.

Difference between spring @Controller and @RestController annotation

Instead of using @Controller and @ResponseBody, @RestController let's you expose Rest APIs in Spring 4.0 and above.

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

How to set RelativeLayout layout params in code not in xml?

I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in MainActivity.java.

package com.example.atul.allison;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;     
    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Layout
            RelativeLayout atulsLayout = new RelativeLayout(this);
            atulsLayout.setBackgroundColor(Color.GREEN);

            //Button
            Button redButton = new Button(this);
            redButton.setText("Log In");
            redButton.setBackgroundColor(Color.RED);

            //Username input
            EditText username =  new EditText(this);

            redButton.setId(1);
            username.setId(2);

            RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            //give rules to position widgets
            usernameDetails.addRule(RelativeLayout.ABOVE,redButton.getId());
            usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            usernameDetails.setMargins(0,0,0,50);

            buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);

            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());
            username.setWidth(px);

            //Add widget to layout(button is now a child of layout)
            atulsLayout.addView(redButton,buttonDetails);
            atulsLayout.addView(username,usernameDetails);

            //Set these activities content/display to this view
            setContentView(atulsLayout);
        }
    }

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

ToList()-- does it create a new list?

Yes, ToList will create a new list, but because in this case MyObject is a reference type then the new list will contain references to the same objects as the original list.

Updating the SimpleInt property of an object referenced in the new list will also affect the equivalent object in the original list.

(If MyObject was declared as a struct rather than a class then the new list would contain copies of the elements in the original list, and updating a property of an element in the new list would not affect the equivalent element in the original list.)

How to load image files with webpack file-loader

Regarding problem #1

Once you have the file-loader configured in the webpack.config, whenever you use import/require it tests the path against all loaders, and in case there is a match it passes the contents through that loader. In your case, it matched

{
    test: /\.(jpe?g|png|gif|svg)$/i, 
    loader: "file-loader?name=/public/icons/[name].[ext]"
}

// For newer versions of Webpack it should be
{
    test: /\.(jpe?g|png|gif|svg)$/i, 
    loader: 'file-loader',
    options: {
      name: '/public/icons/[name].[ext]'
    }
}

and therefore you see the image emitted to

dist/public/icons/imageview_item_normal.png

which is the wanted behavior.

The reason you are also getting the hash file name, is because you are adding an additional inline file-loader. You are importing the image as:

'file!../../public/icons/imageview_item_normal.png'.

Prefixing with file!, passes the file into the file-loader again, and this time it doesn't have the name configuration.

So your import should really just be:

import img from '../../public/icons/imageview_item_normal.png'

Update

As noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):

import '!!file!../../public/icons/imageview_item_normal.png'.

Regarding problem #2

After importing the png, the img variable only holds the path the file-loader "knows about", which is public/icons/[name].[ext] (aka "file-loader? name=/public/icons/[name].[ext]"). Your output dir "dist" is unknown. You could solve this in two ways:

  1. Run all your code under the "dist" folder
  2. Add publicPath property to your output config, that points to your output directory (in your case ./dist).

Example:

output: {
  path: PATHS.build,
  filename: 'app.bundle.js',
  publicPath: PATHS.build
},

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

Angular ng-repeat add bootstrap row every 3 or 4 cols

i solved this using ng-class

<div ng-repeat="item in items">
    <div ng-class="{ 'row': ($index + 1) % 4 == 0 }">
        <div class="col-md-3">
            {{item.name}}
        </div>
    </div>
</div>

C#: Converting byte array to string and printing out to console

I was in a predicament where I had a signed byte array (sbyte[]) as input to a Test class and I wanted to replace it with a normal byte array (byte[]) for simplicity. I arrived here from a Google search but Tom's answer wasn't useful to me.

I wrote a helper method to print out the initializer of a given byte[]:

public void PrintByteArray(byte[] bytes)
{
    var sb = new StringBuilder("new byte[] { ");
    foreach (var b in bytes)
    {
        sb.Append(b + ", ");
    }
    sb.Append("}");
    Console.WriteLine(sb.ToString());
}

You can use it like this:

var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }

The ouput is valid C# which can then just be copied into your code.

And just for completeness, here is the UnsignedBytesFromSignedBytes method:

// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
    var unsigned = new byte[signed.Length];
    Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
    return unsigned;
}

Convert JSONObject to Map

You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.

HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);

return in for loop or outside loop

There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).

This will not mess up garbage collection in any way!!

The better way to do it is to set a boolean value, if you want to listen to him.

boolean flag = false;
for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind) {
        flag = true;
        break;
    }
}
return flag;

Convert interface{} to int

To better understand the type conversion, look at the code below:

package main
import "fmt"
func foo(a interface{}) {
    fmt.Println(a.(int))  // conversion of interface into int
}
func main() {
    var a int = 10
    foo(a)
}

This code executes perfectly and converts interface type to int type

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion. More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

Going back to your code, this

iAreaId := val.(int)

should work good. If you want to check error occured while conversion, you can also re-write above line as

iAreaId, ok := val.(int)

How to copy a char array in C?

You can't directly do array2 = array1, because in this case you manipulate the addresses of the arrays (char *) and not of their inner values (char).

What you, conceptually, want is to do is iterate through all the chars of your source (array1) and copy them to the destination (array2). There are several ways to do this. For example you could write a simple for loop, or use memcpy.

That being said, the recommended way for strings is to use strncpy. It prevents common errors resulting in, for example, buffer overflows (which is especially dangerous if array1 is filled from user input: keyboard, network, etc). Like so:

// Will copy 18 characters from array1 to array2
strncpy(array2, array1, 18);

As @Prof. Falken mentioned in a comment, strncpy can be evil. Make sure your target buffer is big enough to contain the source buffer (including the \0 at the end of the string).

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

In my case i simply removed CFBundleIcons~ipad key from the info.plist file which was blocking the use of AppIcon set for iPad.

The target of my project was iPhone and IOS 8. XCode version was 6.3. Setting CFBundleIcons~ipad probably come from an early version of XCode.

How can I enable the Windows Server Task Scheduler History recording?

I have another possible answer for those wondering why event log entries are not showing up in the History tab of Task Scheduler for certain tasks, even though All Task History is enabled, the events for those tasks are viewable in the Event Log, and all other tasks show history just fine. In my case, I had created 13 new tasks. For 5 of them, events showed fine under History, but for the other 8, the History tab was completely blank. I even verified these tasks were enabled for history individually (and logging events) using Mick Wood's post about using the Event Viewer.

Then it hit me. I suddenly realized what all 8 had in common that the other 5 did not. They all had an ampersand (&) character in the event name. I created them by exporting the first task I created, "Sync E to N", renaming the exported file name, editing the XML contents, and then importing the new task. Windows Explorer happily let me rename the task, for example, to "Sync C to N & T", and Task Scheduler happily let me import it. However, with that pesky "&" in the name, it could not retrieve its history from the event log. When I deleted the original event, renamed the xml file to "Sync C to N and T", and imported it, voila, there were all of the log entries in the History tab in Task Scheduler.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

SqlServer: Login failed for user

For Can not connect to the SQL Server. The original error is: Login failed for user 'username'. error, port requirements on MSSQL server side need to be fulfilled.

There are other ports beyond default port 1433 needed to be configured on Windows Firewall.

https://stackoverflow.com/a/25147251/1608670

Create a button with rounded border

Use OutlineButton instead of FlatButton.

new OutlineButton(
  child: new Text("Button text"),
  onPressed: null,
  shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
)

How do I solve this error, "error while trying to deserialize parameter"

Make sure that the table you are returning has a schema. If not, then create a default schema (i.e. add a column in that table).

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

Here is my simplification:

URN: unique resource name, i.e. "what" (eg urn:issn:1234-5678 ). This is meant to be unique .. as in no two different docs can have the same urn. A bit like "uuid"

URL: "where" to find it ( eg https://google.com/pub?issnid=1234-5678 .. or ftp://somesite.com/doc8.pdf )

URI: can be either a URN or a URL. This fuzzy definition is thanks to RFC 3986 produced by W3C and IETF.

The definition of URI has changed over the years, so it makes sense for most people to be confused. However, you can now take solace in the fact that you can refer to http://somesite.com/something as either a URL or URI ... an you will be right either way (at least fot the time being anyway...)

Remove all HTMLtags in a string (with the jquery text() function)

var myContent = '<div id="test">Hello <span>world!</span></div>';

alert($(myContent).text());

That results in hello world. Does that answer your question?

http://jsfiddle.net/D2tEf/ for an example

Lost connection to MySQL server during query?

I was getting this error with a "broken pipe" when I tried to do bulk inserts with millions of records. I ended up solving this by chunking my data into smaller batch sizes and then running an executemany command with the mysql cursor for each of the inserts I needed to do. This solved the problem and didn't seem to affect the performance in any noticeable way.

eg.

def chunks(data):
    for i in range(0, len(data), CHUNK_SIZE):
        yield data[i:i + CHUNK_SIZE]


def bulk_import(update_list):
    new_list = list(chunks(update_list))
    for batch in new_list:
         cursor.execute(#SQL STATEMENT HERE)

How to remove the arrow from a select element in Firefox

Or, you can clip the select. Something along the lines of:

select { width:200px; position:absolute; clip:rect(0, 170px, 50px, 0); }

This should clip 30px of the right side of select box, stripping away the arrow. Now supply a 170px background image and voila, styled select

How to use cURL to get jSON data and decode the data?

to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

then json_decode() parses JSON into a PHP object, or an array if you pass true to the second parameter. http://php.net/manual/en/function.json-decode.php

For example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

How to pass url arguments (query string) to a HTTP request on Angular?

If you plan on sending more than one parameter.

Component

private options = {
  sort:   '-id',
  select: null,
  limit:  1000,
  skip:   0,
  from:   null,
  to:     null
};

constructor(private service: Service) { }

ngOnInit() {
  this.service.getAllItems(this.options)
    .subscribe((item: Item[]) => {
      this.item = item;
    });
}

Service

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
constructor(private http: Http) { }

getAllItems(query: any) {
  let params: URLSearchParams = new URLSearchParams();
  for(let key in query){
    params.set(key.toString(), query[key]);
  }
  this.options.search = params;
  this.header = this.headers();

And continue with your http request just how @ethemsulan did.

Server side route

router.get('/api/items', (req, res) => {
  let q = {};
  let skip = req.query.skip;
  let limit = req.query.limit;
  let sort  = req.query.sort;
  q.from = req.query.from;
  q.to = req.query.to;

  Items.find(q)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .exec((err, items) => {
      if(err) {
        return res.status(500).json({
          title: "An error occurred",
          error: err
        });
      }
      res.status(200).json({
        message: "Success",
        obj:  items
      });
    });
});

How to change button background image on mouseOver?

I think something like this:

btn.BackgroundImage = Properties.Resources.*Image_Identifier*;

Where *Image_Identifier* is an identifier of the image in your resources.

Include CSS and Javascript in my django template

Refer django docs on static files.

In settings.py:

import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))

MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = 'static/'

STATIC_URL = '/static/'

STATICFILES_DIRS = (
                    os.path.join(CURRENT_PATH, 'static'),
)

Then place your js and css files static folder in your project. Not in media folder.

In views.py:

from django.shortcuts import render_to_response, RequestContext

def view_name(request):
    #your stuff goes here
    return render_to_response('template.html', locals(), context_instance = RequestContext(request))

In template.html:

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>

In urls.py:

from django.conf import settings
urlpatterns += patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

Project file structure can be found here in imgbin.

How to format strings using printf() to get equal length in the output

There's also the %n modifier which can help in certain circumstances. It returns the column on which the string was so far. Example: you want to write several rows that are within the width of the first row like a table.

int width1, width2;
int values[6][2];
printf("|%s%n|%s%n|\n", header1, &width1, header2, &width2);

for(i=0; i<6; i++)
   printf("|%*d|%*d|\n", width1, values[i][0], width2, values[i][1]);

will print two columns of the same width of whatever length the two strings header1 and header2 may have. I don't know if all implementations have the %n, but Solaris and Linux do.

Python script to do something at the same time every day

I spent quite a bit of time also looking to launch a simple Python program at 01:00. For some reason, I couldn't get cron to launch it and APScheduler seemed rather complex for something that should be simple. Schedule (https://pypi.python.org/pypi/schedule) seemed about right.

You will have to install their Python library:

pip install schedule

This is modified from their sample program:

import schedule
import time

def job(t):
    print "I'm working...", t
    return

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

You will need to put your own function in place of job and run it with nohup, e.g.:

nohup python2.7 MyScheduledProgram.py &

Don't forget to start it again if you reboot.

What is the difference between Sublime text and Github's Atom

Another difference is that Sublime text is a closed source project, while Atom source code is/will be publicly available --although Github does not plan to release it as a real open source project. They want to give access to the code, without opening it to contributions.

Github made the code public: http://blog.atom.io/2014/05/06/atom-is-now-open-source.html

How can I call a method in Objective-C?

I think what you're trying to do is:

-(void) score2 {
    [self score];
}

The [object message] syntax is the normal way to call a method in objective-c. I think the @selector syntax is used when the method to be called needs to be determined at run-time, but I don't know well enough to give you more information on that.

How do I pipe or redirect the output of curl -v?

The answer above didn't work for me, what did eventually was this syntax:

curl https://${URL} &> /dev/stdout | tee -a ${LOG}

tee puts the output on the screen, but also appends it to my log.

how to end ng serve or firebase serve

Exit the IDE and boots up IDE again , try it.

Simple pthread! C++

From the pthread function prototype:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine)(void*), void *arg);

The function passed to pthread_create must have a prototype of

void* name(void *arg)

Making an iframe responsive

I found a solution from from Dave Rupert / Chris Coyier. However, I wanted to make the scroll available so I came up with this:

// HTML

<div class="myIframe"> 
   <iframe> </iframe> 
</div>

// CSS

.myIframe {
     position: relative;
     padding-bottom: 65.25%;
     padding-top: 30px;
     height: 0;
     overflow: auto; 
     -webkit-overflow-scrolling:touch; //<<--- THIS IS THE KEY 
     border: solid black 1px;
} 
.myIframe iframe {
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
}

Better way to check if a Path is a File or a Directory?

Here's mine:

    bool IsPathDirectory(string path)
    {
        if (path == null) throw new ArgumentNullException("path");
        path = path.Trim();

        if (Directory.Exists(path)) 
            return true;

        if (File.Exists(path)) 
            return false;

        // neither file nor directory exists. guess intention

        // if has trailing slash then it's a directory
        if (new[] {"\\", "/"}.Any(x => path.EndsWith(x)))
            return true; // ends with slash

        // if has extension then its a file; directory otherwise
        return string.IsNullOrWhiteSpace(Path.GetExtension(path));
    }

It's similar to others' answers but not exactly the same.

Parse HTML table to Python list?

You should use some HTML parsing library like lxml:

from lxml import etree
s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print dict(zip(headers, values))

prints

{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}

How to clear cache in Yarn?

Run yarn cache clean.


Run yarn help cache in your bash, and you will see:

Usage: yarn cache [ls|clean] [flags]

Options: -h, --help output usage information -V, --version output the version number --offline
--prefer-offline
--strict-semver
--json
--global-folder [path]
--modules-folder [path] rather than installing modules into the node_modules folder relative to the cwd, output them here
--packages-root [path] rather than storing modules into a global packages root, store them here
--mutex [type][:specifier] use a mutex to ensure only one yarn instance is executing

Visit http://yarnpkg.com/en/docs/cli/cache for documentation about this command.

Bring element to front using CSS

Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). Use one of those.

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are many ways for doing that (you might want to obfuscate the source code, you can compress it, ...). Some of these methods need additional code to transform your program in an executable form (compression, for example).

But the thing all methods cannot do, is keeping the source code secret. The other party gets your binary code, which can always be transformed (reverse-engineered) into a human-readable form again, because the binary code contains all functionality information that is provided in your source code.

How to access ssis package variables inside script component

Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: screenshot of Script Transformation Editor properties page Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:

// Modify as necessary
public override void PreExecute()
{
    base.PreExecute();
    string thePath = Variables.FilePath;
    // Do something ...
}

public override void PostExecute()
{
    base.PostExecute();
    string theNewValue = "";
    // Do something to figure out the new value...
    Variables.FilePath = theNewValue;
}

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    string thePath = Variables.FilePath;
    // Do whatever needs doing here ...
}

One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.

Regarding the code snippet:

IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;

XlsFile = varCollection["User::FilePath"].Value.ToString();

varCollection is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

What is webpack & webpack-dev-server? Official documentation says it's a module bundler but for me it's just a task runner. What's the difference?

webpack-dev-server is a live reloading web server that Webpack developers use to get immediate feedback what they do. It should only be used during development.

This project is heavily inspired by the nof5 unit test tool.

Webpack as the name implies will create a SINGLE package for the web. The package will be minimized, and combined into a single file (we still live in HTTP 1.1 age). Webpack does the magic of combining the resources (JavaScript, CSS, images) and injecting them like this: <script src="assets/bundle.js"></script>.

It can also be called module bundler because it must understand module dependencies, and how to grab the dependencies and to bundle them together.

Where would you use browserify? Can't we do the same with node/ES6 imports?

You could use Browserify on the exact same tasks where you would use Webpack. – Webpack is more compact, though.

Note that the ES6 module loader features in Webpack2 are using System.import, which not a single browser supports natively.

When would you use gulp/grunt over npm + plugins?

You can forget Gulp, Grunt, Brokoli, Brunch and Bower. Directly use npm command line scripts instead and you can eliminate extra packages like these here for Gulp:

var gulp        = require('gulp'),
  minifyCSS     = require('gulp-minify-css'),
  sass          = require('gulp-sass'),
  browserify    = require('gulp-browserify'),
  uglify        = require('gulp-uglify'),
  rename        = require('gulp-rename'),
  jshint        = require('gulp-jshint'),
  jshintStyle   = require('jshint-stylish'),
  replace       = require('gulp-replace'),
  notify        = require('gulp-notify'),

You can probably use Gulp and Grunt config file generators when creating config files for your project. This way you don't need to install Yeoman or similar tools.

How to hide the border for specified rows of a table?

Use the CSS property border on the <td>s following the <tr>s you do not want to have the border.

In my example I made a class noBorder that I gave to one <tr>. Then I use a simple selector tr.noBorder td to make the border go away for all the <td>s that are inside of <tr>s with the noBorder class by assigning border: 0.

Note that you do not need to provide the unit (i.e. px) if you set something to 0 as it does not matter anyway. Zero is just zero.

_x000D_
_x000D_
table, tr, td {_x000D_
  border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
  border: 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A1</td>_x000D_
    <td>B1</td>_x000D_
    <td>C1</td>_x000D_
  </tr>_x000D_
  <tr class="noBorder">_x000D_
    <td>A2</td>_x000D_
    <td>B2</td>_x000D_
    <td>C2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
    <td>A3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Here's the output as an image:

Output from HTML

How to generate sample XML documents from their DTD or XSD?

The OpenXSD library mentions that they have support for generating XML instances based on the XSD. Check that out.

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

Disable Logback in SpringBoot

Find spring-boot-starter-test in your pom.xml and modify it as follows:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>

It fixed error like:

_Caused by: java.lang.IllegalArgumentException:_ **LoggerFactory** is not a **Logback LoggerContext** but *Logback* is on the classpath.

Either remove **Logback** or the competing implementation

(_class org.apache.logging.slf4j.Log4jLoggerFactory_
loaded from file: 

**${M2_HOME}/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.6.2/log4j-slf4j-impl-2.6.2.jar**).

If you are using WebLogic you will need to add **'org.slf4j'** to prefer-application-packages in WEB-INF/weblogic.xml: **org.apache.logging.slf4j.Log4jLoggerFactory**

WARNING: sanitizing unsafe style value url

Check this handy pipe for Angular2: Usage:

  1. in the SafePipe code, substitute DomSanitizationService with DomSanitizer

  2. provide the SafePipe if your NgModule

  3. <div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>

Finding length of char array

By convention C strings are 'null-terminated'. That means that there's an extra byte at the end with the value of zero (0x00). Any function that does something with a string (like printf) will consider a string to end when it finds null. This also means that if your string is not null terminated, it will keep going until it finds a null character, which can produce some interesting results!

As the first item in your array is 0x00, it will be considered to be length zero (no characters).

If you defined your string to be:

char a[7]={0xdc,0x01,0x04,0x00};

e.g. null-terminated

then you can use strlen to measure the length of the string stored in the array.

sizeof measures the size of a type. It is not what you want. Also remember that the string in an array may be shorter than the size of the array.

Correct Way to Load Assembly, Find Class and Call Run() Method

When you build your assembly, you can call AssemblyBuilder.SetEntryPoint, and then get it back from the Assembly.EntryPoint property to invoke it.

Keep in mind you'll want to use this signature, and note that it doesn't have to be named Main:

static void Run(string[] args)

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

I did everything provided in the previous answers to this question, but still had the issue. I did have the update installed, but I ran the installer again, reapplying the update while SQL 2012 Installer was open on the screen where I could run the check again. After it finished, I ran the check again and it passed.

Writing String to Stream and reading it back does not work

You're using message.Length which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:

byte[] messageBytes = uniEncoding.GetBytes(message);
stringAsStream.Write(messageBytes, 0, messageBytes.Length);

You're then reading a single byte and expecting to get a character from it just by casting to char. UnicodeEncoding will use two bytes per character.

As Justin says you're also not seeking back to the beginning of the stream.

Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter to write and then a StreamReader to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.

Xcode 5 and iOS 7: Architecture and Valid architectures

Simple fix:

Targets -> Build Settings -> Build Options -> Enable Bitcode -> No

Works on device with iOS 9.3.3

How can I get date and time formats based on Culture Info?

You could take a look at the DateTimeFormat property which contains the culture specific formats.

How to set 'X-Frame-Options' on iframe?

If you are following xml approach, then below code will work.

    <security:headers>
        <security:frame-options />
        <security:cache-control />
        <security:content-type-options />
        <security:xss-protection />
    </security:headers>
<security:http>

How to make Sonar ignore some classes for codeCoverage metric?

Sometimes, Clover is configured to provide code coverage reports for all non-test code. If you wish to override these preferences, you may use configuration elements to exclude and include source files from being instrumented:

<plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>maven-clover2-plugin</artifactId>
    <version>${clover-version}</version>
    <configuration> 
        <excludes> 
            <exclude>**/*Dull.java</exclude> 
        </excludes> 
    </configuration>
</plugin>

Also, you can include the following Sonar configuration:

<properties>
    <sonar.exclusions>
        **/domain/*.java,
        **/transfer/*.java
    </sonar.exclusions>
</properties> 

Passing data to components in vue.js

I've found a way to pass parent data to component scope in Vue, i think it's a little a bit of a hack but maybe this will help you.

1) Reference data in Vue Instance as an external object (data : dataObj)

2) Then in the data return function in the child component just return parentScope = dataObj and voila. Now you cann do things like {{ parentScope.prop }} and will work like a charm.

Good Luck!

How to write to a file in Scala?

2019 Update:

Summary - Java NIO (or NIO.2 for async) is still the most comprehensive file processing solution supported in Scala. The following code creates and writes some text to a new file:

import java.io.{BufferedOutputStream, OutputStream}
import java.nio.file.{Files, Paths}

val testFile1 = Paths.get("yourNewFile.txt")
val s1 = "text to insert in file".getBytes()

val out1: OutputStream = new BufferedOutputStream(
  Files.newOutputStream(testFile1))

try {
  out1.write(s1, 0, s1.length)
} catch {
  case _ => println("Exception thrown during file writing")
} finally {
  out1.close()
}
  1. Import Java libraries: IO and NIO
  2. Create a Path object with your chosen file name
  3. Convert your text that you want to insert into a file into a byte array
  4. Get your file as a stream: OutputStream
  5. Pass your byte array into your output stream's write function
  6. Close the stream

Wrapping a react-router Link in an html button

You can use useHistory hook since react-router v5.1.0.

The useHistory hook gives you access to the history instance that you may use to navigate.

import React from 'react'
import { useHistory } from 'react-router-dom'

export default function SomeComponent() {
  const { push } = useHistory()
  ...
  <button
    type="button"
    onClick={() => push('/some-link')}
  >
    Some link
  </button>
  ...
}

Best way to parseDouble with comma as decimal separator?

You of course need to use the correct locale. This question will help.

typedef fixed length array

Arrays can't be passed as function parameters by value in C.

You can put the array in a struct:

typedef struct type24 {
    char byte[3];
} type24;

and then pass that by value, but of course then it's less convenient to use: x.byte[0] instead of x[0].

Your function type24_to_int32(char value[3]) actually passes by pointer, not by value. It's exactly equivalent to type24_to_int32(char *value), and the 3 is ignored.

If you're happy passing by pointer, you could stick with the array and do:

type24_to_int32(const type24 *value);

This will pass a pointer-to-array, not pointer-to-first-element, so you use it as:

(*value)[0]

I'm not sure that's really a gain, since if you accidentally write value[1] then something stupid happens.

Get the size of the screen, current web page and browser window

here is my solution!

_x000D_
_x000D_
// innerWidth_x000D_
const screen_viewport_inner = () => {_x000D_
    let w = window,_x000D_
        i = `inner`;_x000D_
    if (!(`innerWidth` in window)) {_x000D_
        i = `client`;_x000D_
        w = document.documentElement || document.body;_x000D_
    }_x000D_
    return {_x000D_
        width: w[`${i}Width`],_x000D_
        height: w[`${i}Height`]_x000D_
    }_x000D_
};_x000D_
_x000D_
_x000D_
// outerWidth_x000D_
const screen_viewport_outer = () => {_x000D_
    let w = window,_x000D_
        o = `outer`;_x000D_
    if (!(`outerWidth` in window)) {_x000D_
        o = `client`;_x000D_
        w = document.documentElement || document.body;_x000D_
    }_x000D_
    return {_x000D_
        width: w[`${o}Width`],_x000D_
        height: w[`${o}Height`]_x000D_
    }_x000D_
};_x000D_
_x000D_
// style_x000D_
const console_color = `_x000D_
    color: rgba(0,255,0,0.7);_x000D_
    font-size: 1.5rem;_x000D_
    border: 1px solid red;_x000D_
`;_x000D_
_x000D_
_x000D_
_x000D_
// testing_x000D_
const test = () => {_x000D_
    let i_obj = screen_viewport_inner();_x000D_
    console.log(`%c screen_viewport_inner = \n`, console_color, JSON.stringify(i_obj, null, 4));_x000D_
    let o_obj = screen_viewport_outer();_x000D_
    console.log(`%c screen_viewport_outer = \n`, console_color, JSON.stringify(o_obj, null, 4));_x000D_
};_x000D_
_x000D_
// IIFE_x000D_
(() => {_x000D_
    test();_x000D_
})();
_x000D_
_x000D_
_x000D_

Is there a way I can retrieve sa password in sql server 2005

Granted you have administrative Windows privileges on the server, another option would be to start SQL Server in Single User Mode, using the Startup parameter "-m". Doing this, you can login using SQLCMD, create a new user and give it sysadmin privileges. Finally, you have to disable Single User Mode, login to SSMS using your new user, and go to Segurity/Logins and change "sa" user password.

You can check this post: http://v-consult.be/2011/05/26/recover-sa-password-microsoft-sql-server-2008-r2/

keytool error Keystore was tampered with, or password was incorrect

I fixed this issue by deleting the output file and running the command again. It turns out it does NOT overwrite the previous file. I had this issue when renewing a let's encrypt cert with tomcat

filedialog, tkinter and opening files

I had to specify individual commands first and then use the * to bring all in command.

from tkinter import filedialog
from tkinter import *

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

Access denied for user 'root'@'localhost' with PHPMyAdmin

Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:

$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;

Laravel Eloquent Join vs Inner Join?

I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

If you have tables set up something like this:

users
    id
    ...

friends
    id
    user_id
    friend_id
    ...

votes, comments and status_updates (3 tables)
    id
    user_id
    ....

In your User model:

class User extends Eloquent {
    public function friends()
    {
        return $this->hasMany('Friend');
    }
}

In your Friend model:

class Friend extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

$user = User::find(1);
$friends_votes = $user->friends()
    ->with('user') // bring along details of the friend
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
    ->get(['votes.*']); // exclude extra details from friends table

Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.


Edit

To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

$friends_votes = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates = 
    DB::table('status_updates')->where('status_updates.user_id','1')
    ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events = 
    $friends_votes
    ->union($friends_comments)
    ->union($friends_status_updates)
    ->get();

At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.

Clear input fields on form submit

You can access the form over the event:

e.target.reset();

Retrieve column names from java.sql.ResultSet

I know, this question is already answered but probably somebody like me needs to access a column name from DatabaseMetaData by label instead of index:

ResultSet resultSet = null;
DatabaseMetaData metaData = null;

    try {
        metaData  = connection.getMetaData();
        resultSet = metaData.getColumns(null, null, tableName, null);

        while (resultSet.next()){
            String name = resultSet.getString("COLUMN_NAME");
        }
    }

deleting folder from java

Try this:

public static boolean deleteDir(File dir) 
{ 
  if (dir.isDirectory()) 
  { 
    String[] children = dir.list(); 
    for (int i=0; i<children.length; i++)
      return deleteDir(new File(dir, children[i])); 
  }  
  // The directory is now empty or this is a file so delete it 
  return dir.delete(); 
} 

Padding is invalid and cannot be removed?

I came across this error while attempting to pass an un-encrypted file path to the Decrypt method.The solution was to check if the passed file is encrypted first before attempting to decrypt

if (Sec.IsFileEncrypted(e.File.FullName))
{
    var stream = Sec.Decrypt(e.File.FullName);
} 
else
{
    // non-encrypted scenario  
}

How can I apply styles to multiple classes at once?

just seperate the class name with a comma.

.a,.b{
your styles
}

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

Excel "External table is not in the expected format."

If you still have this problem, then check your permissions, I tried many of these suggestions and my concrete problem was that the file that I wanted to process was under source control and the thread had no permissions, I had to change the entire folder permissions and it started to work (I was processing many files in there)... It also matches many suggestions like change the name of the file or check that the file is not loicked by another process.

I hope it helps you.

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

How to get the public IP address of a user in C#

 private string GetClientIpaddress()
    {
        string ipAddress = string.Empty;
        ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (ipAddress == "" || ipAddress == null)
        {
            ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            return ipAddress;
        }
        else
        {
            return ipAddress;
        }
    }

Can we instantiate an abstract class?

You can simply answers, in just one line

No, you can never instance Abstract Class

But, interviewer still not agree, then you can tell him/her

all you can do is, you can create an Anonymous Class.

And, according to Anonymous class, class declared and instantiate at the same place/line

So, it might be possible that, interviewer would be interested to check your confidence level and how much you know about the OOPs .

Insert/Update Many to Many Entity Framework . How do I do it?

I use the following way to handle the many-to-many relationship where only foreign keys are involved.

So for inserting:

public void InsertStudentClass (long studentId, long classId)
{
    using (var context = new DatabaseContext())
    {
        Student student = new Student { StudentID = studentId };
        context.Students.Add(student);
        context.Students.Attach(student);

        Class class = new Class { ClassID = classId };
        context.Classes.Add(class);
        context.Classes.Attach(class);

        student.Classes = new List<Class>();
        student.Classes.Add(class);

        context.SaveChanges();
    }
}

For deleting,

public void DeleteStudentClass(long studentId, long classId)
{
    Student student = context.Students.Include(x => x.Classes).Single(x => x.StudentID == studentId);

    using (var context = new DatabaseContext())
    {
        context.Students.Attach(student);
        Class classToDelete = student.Classes.Find(x => x.ClassID == classId);
        if (classToDelete != null)
        {
            student.Classes.Remove(classToDelete);
            context.SaveChanges();
        }
    }
}

How to set focus on an input field after rendering?

AutoFocus worked best for me. I needed to change some text to an input with that text on double click so this is what I ended up with:

<input autoFocus onFocus={this.setCaretToEnd} value={this.state.editTodo.value} onDoubleClick={this.updateTodoItem} />

NOTE: To fix the issue where React places the caret at the beginning of the text use this method:

setCaretToEnd(event) {
    var originalText = event.target.value;
    event.target.value = '';
    event.target.value = originalText;
}

Found here: https://coderwall.com/p/0iz_zq/how-to-put-focus-at-the-end-of-an-input-with-react-js

C# Clear all items in ListView

Try with this:

myListView.ItemsSource = new List< DictionaryEntry >();

NTFS performance and large volumes of files and directories

For local access, large numbers of directories/files doesn't seem to be an issue. However, if you're accessing it across a network, there's a noticeable performance hit after a few hundred (especially when accessed from Vista machines (XP to Windows Server w/NTFS seemed to run much faster in that regard)).

Get element inside element by class and ID - JavaScript

Recursive function :

function getElementInsideElement(baseElement, wantedElementID) {
    var elementToReturn;
    for (var i = 0; i < baseElement.childNodes.length; i++) {
        elementToReturn = baseElement.childNodes[i];
        if (elementToReturn.id == wantedElementID) {
            return elementToReturn;
        } else {
            return getElementInsideElement(elementToReturn, wantedElementID);
        }
    }
}

How to get the insert ID in JDBC?

  1. Create Generated Column

    String generatedColumns[] = { "ID" };
    
  2. Pass this geneated Column to your statement

    PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
    
  3. Use ResultSet object to fetch the GeneratedKeys on Statement

    ResultSet rs = stmtInsert.getGeneratedKeys();
    
    if (rs.next()) {
        long id = rs.getLong(1);
        System.out.println("Inserted ID -" + id); // display inserted record
    }
    

How to Change color of Button in Android when Clicked?

One approach is to create an XML file like this in drawable, called whatever.xml:

<?xml version="1.0" encoding="utf-8"?> 
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/bgalt" />

    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/bgalt" />

    <item android:drawable="@drawable/bgnorm" />
</selector>

bgalt and bgnormare PNG images in drawable.

If you create the buttons programatically in your activity, you can set the background with:

final Button b = new Button (MyClass.this);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));

If you set your buttons' style with an XML, you would do something like:

<Button
  android:id="@+id/mybutton"
  android:background="@drawable/watever" />

And finally a link to a tutorial. Hope this helps.

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

Java: Detect duplicates in ArrayList?

Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.

List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);

if(set.size() < list.size()){
    /* There are duplicates */
}

Update: If I'm understanding your question correctly, you have a 2d array of Block, as in

Block table[][];

and you want to detect if any row of them has duplicates?

In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:

for (Block[] row : table) {
   Set set = new HashSet<Block>(); 
   for (Block cell : row) {
      set.add(cell);
   }
   if (set.size() < 6) { //has duplicate
   }
}

I'm not 100% sure of that for syntax, so it might be safer to write it as

for (int i = 0; i < 6; i++) {
   Set set = new HashSet<Block>(); 
   for (int j = 0; j < 6; j++)
    set.add(table[i][j]);
 ...

Set.add returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false if all you want to know is whether there are any duplicates.

How do I make my string comparison case insensitive?

Note that you may want to do null checks on them as well prior to doing your .equals or .equalsIgnoreCase.

A null String object can not call an equals method.

ie:

public boolean areStringsSame(String str1, String str2)
{
    if (str1 == null && str2 == null)
        return true;
    if (str1 == null || str2 == null)
        return false;

    return str1.equalsIgnoreCase(str2);
}

How to fix corrupted git repository?

Remove the index and do reset

rm -f .git/index
git reset

Multi-line bash commands in makefile

Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo depend on itself, but of course, make is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.

GNU make knows how to run gcc to produce an executable out of a set of .c and .h files, so maybe all you really need amounts to

foo: $(wildcard *.h) $(wildcard *.c)

Remove an item from an IEnumerable<T> collection

Try turning the IEnumerable into a List. From this point on you will be able to use List's Remove method to remove items.

To pass it as a param to the Remove method using Linq you can get the item by the following methods:

  • users.Single(x => x.userId == 1123)
  • users.First(x => x.userId == 1123)

The code is as follows:

users = users.ToList(); // Get IEnumerable as List

users.Remove(users.First(x => x.userId == 1123)); // Remove item

// Finished

Why does git status show branch is up-to-date when changes exist upstream?

Trivial answer yet accurate in some cases, such as the one that brought me here. I was working in a repo which was new for me and I added a file which was not seen as new by the status.

It ends up that the file matched a pattern in the .gitignore file.

Creating a static class with no instances

The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.

That is, the Pythonic way would be:

# My module
elements = []

def add_element(x):
  elements.append(x)

But if you want to mirror the structure of Java, you can do:

# My module
class World(object):
  elements = []

  @staticmethod
  def add_element(x):
    World.elements.append(x)

You can also do this with @classmethod if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):

# My module
class World(object):
  elements = []

  @classmethod
  def add_element(cls, x):
    cls.elements.append(x)

'react-scripts' is not recognized as an internal or external command

This worked for me:

  • Go to the project folder in CLI and type npm install.Go for a similar command if using yarn etc.

  • Then type npm start if you are using Npm. Go for a similar command if using yarn etc.

  • The file starts working

What is the use of BindingResult interface in spring MVC?

Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.

Then, you can check this object looking for validation errors:

validator.validate(modelObject, bindingResult);  
if (bindingResult.hasErrors()) {  
    // do something  
}

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

I had this problem in a unit test which opened a lot of connections to the DB via a connection pool and then "stopped" the connection pool (ManagedDataSource actually) to release the connections at the end of the each test. I always ran out of connections at some point in the suite of tests.

Added a Thread.sleep(500) in the teardown() of my tests and this resolved the issue. I think that what was happening was that the connection pool stop() releases the active connections in another thread so that if the main thread keeps running tests the cleanup thread(s) got so far behind that the Oracle server ran out of connections. Adding the sleep allows the background threads to release the pooled connections.

This is much less of an issue in the real world because the DB servers are much bigger and there is a healthy mix of operations (not just endless DB connect/disconnect operations).

Simple state machine example in C#?

You can code an iterator block that lets you execute a code block in an orchestrated fashion. How the code block is broken up really doesn't have to correspond to anything, it's just how you want to code it. For example:

IEnumerable<int> CountToTen()
{
    System.Console.WriteLine("1");
    yield return 0;
    System.Console.WriteLine("2");
    System.Console.WriteLine("3");
    System.Console.WriteLine("4");
    yield return 0;
    System.Console.WriteLine("5");
    System.Console.WriteLine("6");
    System.Console.WriteLine("7");
    yield return 0;
    System.Console.WriteLine("8");
    yield return 0;
    System.Console.WriteLine("9");
    System.Console.WriteLine("10");
}

In this case, when you call CountToTen, nothing actually executes, yet. What you get is effectively a state machine generator, for which you can create a new instance of the state machine. You do this by calling GetEnumerator(). The resulting IEnumerator is effectively a state machine that you can drive by calling MoveNext(...).

Thus, in this example, the first time you call MoveNext(...) you will see "1" written to the console, and the next time you call MoveNext(...) you will see 2, 3, 4, and then 5, 6, 7 and then 8, and then 9, 10. As you can see, it's a useful mechanism for orchestrating how things should occur.

How do I determine height and scrolling position of window in jQuery?

$(window).height()

$(window).width()

There is also a plugin to jquery to determine element location and offsets

http://plugins.jquery.com/project/dimensions

scrolling offset = offsetHeight property of an element

How to scroll to the bottom of a UITableView on the iPhone before the view appears

Details

  • Xcode 8.3.2, swift 3.1
  • Xcode 10.2 (10E125), Swift 5

Code

import UIKit

extension UITableView {
    func scrollToBottom(animated: Bool) {
        let y = contentSize.height - frame.size.height
        if y < 0 { return }
        setContentOffset(CGPoint(x: 0, y: y), animated: animated)
    }
}

Usage

tableView.scrollToBottom(animated: true)

Full sample

Do not forget to paste solution code!

import UIKit

class ViewController: UIViewController {

    private weak var tableView: UITableView?
    private lazy var cellReuseIdentifier = "CellReuseIdentifier"

    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: view.frame)
        view.addSubview(tableView)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        self.tableView = tableView
        tableView.dataSource = self
        tableView.performBatchUpdates(nil) { [weak self] result in
            if result { self?.tableView?.scrollToBottom(animated: true) }
        }
    }
}

extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath )
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

Vertical divider doesn't work in Bootstrap 3

I think this will bring it back using 3.0

.navbar .divider-vertical {
    height: 50px;
    margin: 0 9px;
    border-right: 1px solid #ffffff;
    border-left: 1px solid #f2f2f2;
}

.navbar-inverse .divider-vertical {
    border-right-color: #222222;
    border-left-color: #111111;
}

@media (max-width: 767px) {
    .navbar-collapse .nav > .divider-vertical {
        display: none;
     }
}

Convert array of JSON object strings to array of JS objects

If you really have:

var s = ['{"Select":"11", "PhotoCount":"12"}','{"Select":"21", "PhotoCount":"22"}'];

then simply:

var objs = $.map(s, $.parseJSON);

Here's a demo.

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

List files ONLY in the current directory

this can be done with os.walk()

python 3.5.2 tested;

import os
for root, dirs, files in os.walk('.', topdown=True):
    dirs.clear() #with topdown true, this will prevent walk from going into subs
    for file in files:
      #do some stuff
      print(file)

remove the dirs.clear() line and the files in sub folders are included again.

update with references;

os.walk documented here and talks about the triple list being created and topdown effects.

.clear() documented here for emptying a list

so by clearing the relevant list from os.walk you can effect its result to your needs.

COALESCE with Hive SQL

Hive supports bigint literal since 0.8 version. So, additional "L" is enough:

COALESCE(column, 0L)

What's the difference between :: (double colon) and -> (arrow) in PHP?

The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.

The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.

The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.

Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.

How to get previous page url using jquery

We have document.referrer for this, but it is not on which we can relay. This could be saved, could be not

$(document).ready(function() {
   var referrer =  document.referrer;
});

The better approach is to add a cookie to store the previous-url in the browser.

How to add a right button to a UINavigationController?

-(void) viewWillAppear:(BOOL)animated
{

    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRight setFrame:CGRectMake(0, 0, 30, 44)];
    [btnRight setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    [btnRight addTarget:self action:@selector(saveData) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBtnRight = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    [barBtnRight setTintColor:[UIColor whiteColor]];
    [[[self tabBarController] navigationItem] setRightBarButtonItem:barBtnRight];

}

Should methods in a Java interface be declared with or without a public access modifier?

I prefer skipping it, I read somewhere that interfaces are by default, public and abstract.

To my surprise the book - Head First Design Patterns, is using public with interface declaration and interface methods... that made me rethink once again and I landed up on this post.

Anyways, I think redundant information should be ignored.

AppCompat v7 r21 returning error in values.xml?

I have updated the build.gradle(Module: app): Old Code:

  compile 'com.android.support:appcompat-v7:23.0.1'

New Code:

 compile 'com.android.support:appcompat-v7:22.2.0'

Works for me in android studio.

Correct way to quit a Qt program?

While searching this very question I discovered this example in the documentation.

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);

Mutatis mutandis for your particular action of course.

Along with this note.

It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()

How do you create a Swift Date object?

Swift has its own Date type. No need to use NSDate.

Creating a Date and Time in Swift

In Swift, dates and times are stored in a 64-bit floating point number measuring the number of seconds since the reference date of January 1, 2001 at 00:00:00 UTC. This is expressed in the Date structure. The following would give you the current date and time:

let currentDateTime = Date()

For creating other date-times, you can use one of the following methods.

Method 1

If you know the number of seconds before or after the 2001 reference date, you can use that.

let someDateTime = Date(timeIntervalSinceReferenceDate: -123456789.0) // Feb 2, 1997, 10:26 AM

Method 2

Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date. For this you can use DateComponents to specify the components and then Calendar to create the date. The Calendar gives the Date context. Otherwise, how would it know what time zone or calendar to express it in?

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1980
dateComponents.month = 7
dateComponents.day = 11
dateComponents.timeZone = TimeZone(abbreviation: "JST") // Japan Standard Time
dateComponents.hour = 8
dateComponents.minute = 34

// Create date from components
let userCalendar = Calendar(identifier: .gregorian) // since the components above (like year 1980) are for Gregorian
let someDateTime = userCalendar.date(from: dateComponents)

Other time zone abbreviations can be found here. If you leave that blank, then the default is to use the user's time zone.

Method 3

The most succinct way (but not necessarily the best) could be to use DateFormatter.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let someDateTime = formatter.date(from: "2016/10/08 22:31")

The Unicode technical standards show other formats that DateFormatter supports.

Notes

See my full answer for how to display the date and time in a readable format. Also read these excellent articles:

Check if an element contains a class in JavaScript?

  1. Felix's trick of adding spaces to flank the className and the string you're searching for is the right approach to determining whether the elements has the class or not.

  2. To have different behaviour according to the class, you may use function references, or functions, within a map:

    function fn1(element){ /* code for element with class1 */ }
    
    function fn2(element){ /* code for element with class2 */ }
    
    function fn2(element){ /* code for element with class3 */ }
    
    var fns={'class1': fn1, 'class2': fn2, 'class3': fn3};
    
    for(var i in fns) {
        if(hasClass(test, i)) {
            fns[i](test);
        }
    }
    
    • for(var i in fns) iterates through the keys within the fns map.
    • Having no break after fnsi allows the code to be executed whenever there is a match - so that if the element has, f.i., class1 and class2, both fn1 and fn2 will be executed.
    • The advantage of this approach is that the code to execute for each class is arbitrary, like the one in the switch statement; in your example all the cases performed a similar operation, but tomorrow you may need to do different things for each.
    • You may simulate the default case by having a status variable telling whether a match was found in the loop or not.

Double precision - decimal places

A double holds 53 binary digits accurately, which is ~15.9545898 decimal digits. The debugger can show as many digits as it pleases to be more accurate to the binary value. Or it might take fewer digits and binary, such as 0.1 takes 1 digit in base 10, but infinite in base 2.

This is odd, so I'll show an extreme example. If we make a super simple floating point value that holds only 3 binary digits of accuracy, and no mantissa or sign (so range is 0-0.875), our options are:

binary - decimal
000    - 0.000
001    - 0.125
010    - 0.250
011    - 0.375
100    - 0.500
101    - 0.625
110    - 0.750
111    - 0.875

But if you do the numbers, this format is only accurate to 0.903089987 decimal digits. Not even 1 digit is accurate. As is easy to see, since there's no value that begins with 0.4?? nor 0.9??, and yet to display the full accuracy, we require 3 decimal digits.

tl;dr: The debugger shows you the value of the floating point variable to some arbitrary precision (19 digits in your case), which doesn't necessarily correlate with the accuracy of the floating point format (17 digits in your case).

initializing a Guava ImmutableMap

"put" has been deprecated, refrain from using it, use .of instead

ImmutableMap<String, String> myMap = ImmutableMap.of(
    "city1", "Seattle",
    "city2", "Delhi"
);

Undoing accidental git stash pop

From git stash --help

Recovering stashes that were cleared/dropped erroneously
   If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
   following incantation to get a list of stashes that are still in your repository, but not reachable any more:

       git fsck --unreachable |
       grep commit | cut -d\  -f3 |
       xargs git log --merges --no-walk --grep=WIP

This helped me better than the accepted answer with the same scenario.

How to autoplay HTML5 mp4 video on Android?

<video autoplay controls id='video1' width='100%' poster='images/top_icon.png' webkitEnterFullscreen poster preload='true'>
<source src='http://192.xxx.xxx.xx/XXXXVM01.mp4' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2' >
</video>

How to clear the text of all textBoxes in the form?

Your textboxes are probably inside of panels or other containers, and not directly inside the form.

You need to recursively traverse the Controls collection of every child control.

replace NULL with Blank value or Zero in sql server

The coalesce() is the best solution when there are multiple columns [and]/[or] values and you want the first one. However, looking at books on-line, the query optimize converts it to a case statement.

MSDN excerpt

The COALESCE expression is a syntactic shortcut for the CASE expression.

That is, the code COALESCE(expression1,...n) is rewritten by the query optimizer as the following CASE expression:

CASE
   WHEN (expression1 IS NOT NULL) THEN expression1
   WHEN (expression2 IS NOT NULL) THEN expression2
   ...
   ELSE expressionN
END

With that said, why not a simple ISNULL()? Less code = better solution?

Here is a complete code snippet.

-- drop the test table
drop table #temp1
go

-- create test table
create table #temp1
(
    issue varchar(100) NOT NULL,
    total_amount int NULL
); 
go

-- create test data
insert into #temp1 values
    ('No nulls here', 12),
    ('I am a null', NULL);
go

-- isnull works fine
select
    isnull(total_amount, 0) as total_amount  
from #temp1

Last but not least, how are you getting null values into a NOT NULL column?

I had to change the table definition so that I could setup the test case. When I try to alter the table to NOT NULL, it fails since it does a nullability check.

-- this alter fails
alter table #temp1 alter column total_amount int NOT NULL

Form Submit Execute JavaScript Best Practice?

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

How to properly validate input values with React.JS?

Your jsfiddle does not work anymore. I've fixed it: http://jsfiddle.net/tkrotoff/bgC6E/40/ using React 16 and ES6 classes.

class Adaptive_Input extends React.Component {
  handle_change(e) {
    var new_text = e.currentTarget.value;
    this.props.on_Input_Change(new_text);
  }

  render() {
    return (
      <div className="adaptive_placeholder_input_container">
        <input
          className="adaptive_input"
          type="text"
          required="required"
          onChange={this.handle_change.bind(this)} />
        <label
          className="adaptive_placeholder"
          alt={this.props.initial}
          placeholder={this.props.focused} />
      </div>
    );
  }
}

class Form extends React.Component {
  render() {
    return (
      <form>
        <Adaptive_Input
          initial={'Name Input'}
          focused={'Name Input'}
          on_Input_Change={this.props.handle_text_input} />

        <Adaptive_Input
          initial={'Value 1'}
          focused={'Value 1'}
          on_Input_Change={this.props.handle_value_1_input} />

        <Adaptive_Input
          initial={'Value 2'}
          focused={'Value 2'}
          on_Input_Change={this.props.handle_value_2_input} />
      </form>
    );
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Name: 'No Name',
      Value_1: '0',
      Value_2: '0',
      Display_Value: '0'
    };
  }

  handle_text_input(new_text) {
    this.setState({
      Name: new_text
    });
  }

  handle_value_1_input(new_value) {
    new_value = parseInt(new_value);
    var updated_display = new_value + parseInt(this.state.Value_2);
    updated_display = updated_display.toString();
    this.setState({
      Value_1: new_value,
      Display_Value: updated_display
    });
  }

  handle_value_2_input(new_value) {
    new_value = parseInt(new_value);
    var updated_display = parseInt(this.state.Value_1) + new_value;
    updated_display = updated_display.toString();
    this.setState({
      Value_2: new_value,
      Display_Value: updated_display
    });
  }

  render() {
    return(
      <div>
        <h2>{this.state.Name}</h2>
        <h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
        <Form
          handle_text_input={this.handle_text_input.bind(this)}
          handle_value_1_input={this.handle_value_1_input.bind(this)}
          handle_value_2_input={this.handle_value_2_input.bind(this)}
        />
      </div>
    );
  }
}

ReactDOM.render(<Page />, document.getElementById('app'));

And now the same code hacked with form validation thanks to this library: https://github.com/tkrotoff/react-form-with-constraints => http://jsfiddle.net/tkrotoff/k4qa4heg/

http://jsfiddle.net/tkrotoff/k4qa4heg/

const { FormWithConstraints, FieldFeedbacks, FieldFeedback } = ReactFormWithConstraints;

class Adaptive_Input extends React.Component {
  static contextTypes = {
    form: PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);

    this.state = {
      field: undefined
    };

    this.fieldWillValidate = this.fieldWillValidate.bind(this);
    this.fieldDidValidate = this.fieldDidValidate.bind(this);
  }

  componentWillMount() {
    this.context.form.addFieldWillValidateEventListener(this.fieldWillValidate);
    this.context.form.addFieldDidValidateEventListener(this.fieldDidValidate);
  }

  componentWillUnmount() {
    this.context.form.removeFieldWillValidateEventListener(this.fieldWillValidate);
    this.context.form.removeFieldDidValidateEventListener(this.fieldDidValidate);
  }

  fieldWillValidate(fieldName) {
    if (fieldName === this.props.name) this.setState({field: undefined});
  }

  fieldDidValidate(field) {
    if (field.name === this.props.name) this.setState({field});
  }

  handle_change(e) {
    var new_text = e.currentTarget.value;
    this.props.on_Input_Change(e, new_text);
  }

  render() {
    const { field } = this.state;
    let className = 'adaptive_placeholder_input_container';
    if (field !== undefined) {
      if (field.hasErrors()) className += ' error';
      if (field.hasWarnings()) className += ' warning';
    }

    return (
      <div className={className}>
        <input
          type={this.props.type}
          name={this.props.name}
          className="adaptive_input"
          required
          onChange={this.handle_change.bind(this)} />
        <label
          className="adaptive_placeholder"
          alt={this.props.initial}
          placeholder={this.props.focused} />
      </div>
    );
  }
}

class Form extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Name: 'No Name',
      Value_1: '0',
      Value_2: '0',
      Display_Value: '0'
    };
  }

  handle_text_input(e, new_text) {
    this.form.validateFields(e.currentTarget);

    this.setState({
      Name: new_text
    });
  }

  handle_value_1_input(e, new_value) {
    this.form.validateFields(e.currentTarget);

    if (this.form.isValid()) {
      new_value = parseInt(new_value);
      var updated_display = new_value + parseInt(this.state.Value_2);
      updated_display = updated_display.toString();
      this.setState({
        Value_1: new_value,
        Display_Value: updated_display
      });
    }
    else {
      this.setState({
        Display_Value: 'Error'
      });
    }
  }

  handle_value_2_input(e, new_value) {
    this.form.validateFields(e.currentTarget);

    if (this.form.isValid()) {
      new_value = parseInt(new_value);
      var updated_display = parseInt(this.state.Value_1) + new_value;
      updated_display = updated_display.toString();
      this.setState({
        Value_2: new_value,
        Display_Value: updated_display
      });
    }
    else {
      this.setState({
        Display_Value: 'Error'
      });
    }
  }

  render() {
    return(
      <div>
        <h2>Name: {this.state.Name}</h2>
        <h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>

        <FormWithConstraints ref={form => this.form = form} noValidate>
          <Adaptive_Input
            type="text"
            name="name_input"
            initial={'Name Input'}
            focused={'Name Input'}
            on_Input_Change={this.handle_text_input.bind(this)} />
          <FieldFeedbacks for="name_input">
            <FieldFeedback when="*" error />
            <FieldFeedback when={value => !/^\w+$/.test(value)} warning>Should only contain alphanumeric characters</FieldFeedback>
          </FieldFeedbacks>

          <Adaptive_Input
            type="number"
            name="value_1_input"
            initial={'Value 1'}
            focused={'Value 1'}
            on_Input_Change={this.handle_value_1_input.bind(this)} />
          <FieldFeedbacks for="value_1_input">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <Adaptive_Input
            type="number"
            name="value_2_input"
            initial={'Value 2'}
            focused={'Value 2'}
            on_Input_Change={this.handle_value_2_input.bind(this)} />
          <FieldFeedbacks for="value_2_input">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </FormWithConstraints>
      </div>
    );
  }
}

ReactDOM.render(<Form />, document.getElementById('app'));

The proposed solution here is hackish as I've tried to keep it close to the original jsfiddle. For proper form validation with react-form-with-constraints, check https://github.com/tkrotoff/react-form-with-constraints#examples

Find and replace with a newline in Visual Studio Code

CTRL + H, then select regex (*) and write \n

Shorter version: CTRL+H ALT+R \n

What does the question mark and the colon (?: ternary operator) mean in objective-c?

This is part of C, so it's not Objective-C specific. Here's a translation into an if statement:

if (inPseudoEditMode)
    label.frame = kLabelIndentedRec;
else
    label.frame = kLabelRect;

Multiline string literal in C#

You can use @ and "".

        string sourse = @"{
        ""items"":[
        {
            ""itemId"":0,
            ""name"":""item0""
        },
        {
            ""itemId"":1,
            ""name"":""item1""
        }
        ]
    }";

Retrieve version from maven pom.xml in code

Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:

mvn help:evaluate -Dexpression=project.version -q -DforceStdout

Usage example:

VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar

How to use systemctl in Ubuntu 14.04

I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.

If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.

For enable, the generic looks to be the following:

update-rc.d <service> enable

Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers

Java: How can I compile an entire directory structure of code ?

I would take Jon's suggestion and use Ant, since this is a pretty complex task.

However, if you are determined to get it all in one line in the Terminal, on Linux you could use the find command. But I don't recommend this at all, since there's no guarantee that, say, Foo.java will be compiled after Bar.java, even though Foo uses Bar. An example would be:

find . -type f -name "*.java" -exec javac {} \;

If all of your classes haven't been compiled yet, if there's one main harness or driver class (basically the one containing your main method), compiling that main class individually should compile most of project, even if they are in different folders, since Javac will try to the best of its abilities to resolve dependency issues.

Multiple selector chaining in jQuery?

$("#Create").find(".myClass").add("#Edit .myClass").plugin({});

Use $.fn.add to concatenate two sets.

How to 'bulk update' with Django?

Django 2.2 version now has a bulk_update method (release notes).

https://docs.djangoproject.com/en/stable/ref/models/querysets/#bulk-update

Example:

# get a pk: record dictionary of existing records
updates = YourModel.objects.filter(...).in_bulk()
....
# do something with the updates dict
....
if hasattr(YourModel.objects, 'bulk_update') and updates:
    # Use the new method
    YourModel.objects.bulk_update(updates.values(), [list the fields to update], batch_size=100)
else:
    # The old & slow way
    with transaction.atomic():
        for obj in updates.values():
            obj.save(update_fields=[list the fields to update])

How to get two or more commands together into a batch file

if I understand you right (not sure), the start parameter /D should help you:

start "cmd" /D %PathName% %comd%

/D sets the start-directory (see start /?)

Git Push Error: insufficient permission for adding an object to repository database

I was getting this problem with a remote repository on a Samba share; I pulled successfully from this remote, but failed when pushing to it.

The cause of the error was incorrect credentials in my ~/.smbcredentials file.

Where is the WPF Numeric UpDown control?

You can use NumericUpDown control for WPF written by me as a part of WPFControls library.

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

NGinx Default public www location?

in ubuntu 19.04, we found it on

/usr/share/nginx/html

Center Triangle at Bottom of Div

I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

How to make multiple divs display in one line but still retain width?

Flex is the better way. Just try..

display: flex;

How do you push a Git tag to a branch using a refspec?

I create the tag like this and then I push it to GitHub:

git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags

Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
 * [new tag]         v1.1 -> v1.1

How to create a DB link between two oracle instances

as a simple example:

CREATE DATABASE LINK _dblink_name_
  CONNECT TO _username_
    IDENTIFIED BY _passwd_
      USING '$_ORACLE_SID_'

for more info: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm

How to conditionally take action if FINDSTR fails to find a string

I tried to get this working using FINDSTR, but for some reason my "debugging" command always output an error level of 0:

ECHO %ERRORLEVEL%

My workaround is to use Grep from Cygwin, which outputs the right errorlevel (it will give an errorlevel greater than 0) if a string is not found:

dir c:\*.tib >out 2>>&1
grep "1 File(s)" out
IF %ERRORLEVEL% NEQ 0 "Run other commands" ELSE "Run Errorlevel 0 commands"

Cygwin's grep will also output errorlevel 2 if the file is not found. Here's the hash from my version:

C:\temp\temp>grep --version grep (GNU grep) 2.4.2

C:\cygwin64\bin>md5sum grep.exe c0a50e9c731955628ab66235d10cea23 *grep.exe

C:\cygwin64\bin>sha1sum grep.exe ff43a335bbec71cfe99ce8d5cb4e7c1ecdb3db5c *grep.exe

iOS start Background Thread

Enable NSZombieEnabled to know which object is being released and then accessed. Then check if the getResultSetFromDB: has anything to do with that. Also check if docids has anything inside and if it is being retained.

This way you can be sure there is nothing wrong.

What is java pojo class, java bean, normal class?

POJO stands for Plain Old Java Object, and would be used to describe the same things as a "Normal Class" whereas a JavaBean follows a set of rules. Most commonly Beans use getters and setters to protect their member variables, which are typically set to private and have a no-argument public constructor. Wikipedia has a pretty good rundown of JavaBeans: http://en.wikipedia.org/wiki/JavaBeans

POJO is usually used to describe a class that doesn't need to be a subclass of anything, or implement specific interfaces, or follow a specific pattern.

How to output only captured groups with sed?

run(s) of digits

This answer works with any count of digit groups. Example:

$ echo 'Num123that456are7899900contained0018166intext' \
   | sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'

123 456 7899900 0018166

Expanded answer.

Is there any way to tell sed to output only captured groups?

Yes. replace all text by the capture group:

$ echo 'Number 123 inside text' \
   | sed 's/[^0-9]*\([0-9]\{1,\}\)[^0-9]*/\1/'

123
s/[^0-9]*                           # several non-digits
         \([0-9]\{1,\}\)            # followed by one or more digits
                        [^0-9]*     # and followed by more non-digits.
                               /\1/ # gets replaced only by the digits.

Or with extended syntax (less backquotes and allow the use of +):

$ echo 'Number 123 in text' \
   | sed -E 's/[^0-9]*([0-9]+)[^0-9]*/\1/'

123

To avoid printing the original text when there is no number, use:

$ echo 'Number xxx in text' \
   | sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1/p'
  • (-n) Do not print the input by default.
  • (/p) print only if a replacement was done.

And to match several numbers (and also print them):

$ echo 'N 123 in 456 text' \
  | sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1 /gp'

123 456

That works for any count of digit runs:

$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" \
   | sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'

123 456 7899900 0018166

Which is very similar to the grep command:

$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" | grep -Po '\d+'
123
456
7899900
0018166

About \d

and pattern: /([\d]+)/

Sed does not recognize the '\d' (shortcut) syntax. The ascii equivalent used above [0-9] is not exactly equivalent. The only alternative solution is to use a character class: '[[:digit:]]`.

The selected answer use such "character classes" to build a solution:

$ str='This is a sample 123 text and some 987 numbers'
$ echo "$str" | sed -rn 's/[^[:digit:]]*([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)[^[:digit:]]*/\1 \2/p'

That solution only works for (exactly) two runs of digits.

Of course, as the answer is being executed inside the shell, we can define a couple of variables to make such answer shorter:

$ str='This is a sample 123 text and some 987 numbers'
$ d=[[:digit:]]     D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D+($d+)$D*/\1 \2/p"

But, as has been already explained, using a s/…/…/gp command is better:

$ str='This is 75577 a sam33ple 123 text and some 987 numbers'
$ d=[[:digit:]]     D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D*/\1 /gp"
75577 33 123 987

That will cover both repeated runs of digits and writing a short(er) command.

Tar archiving that takes input from a list of files

On Solaris, you can use the option -I to read the filenames that you would normally state on the command line from a file. In contrast to the command line, this can create tar archives with hundreds of thousands of files (just did that).

So the example would read

tar -cvf allfiles.tar -I mylist.txt

In SQL Server, how to create while loop in select

  1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
  2. Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.

How to convert a date string to different format

If you can live with 01 for January instead of 1, then try...

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")

You can check the docs for other formatting directives.

How to use mongoimport to import csv

When I was trying to import the CSV file, I was getting an error. What I have done. First I changed the header line's column names in Capital letter and removed "-" and added "_" if needed. Then Typed below command for importing CSV into mongo

$ mongoimport --db=database_name --collection=collection_name --type=csv --file=file_name.csv --headerline  

enter image description here

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

if your certificate is not valid, it will have a red "x" and state the reason why. Generally the reason is "This certificate has expired" or "This certificate was signed by an unknown authority.

to solve this you need to do the following step.

  1. If your certificate has expired, renew it at the iPhone Portal, download it, and double-click it to add it to your Keychain.
  2. If it's "signed by an unknown authority", download the "Apple Worldwide Developer Relations" certificate from the Certificates section of the iPhone Developer portal and double-click it to add it to your Keychain.
  3. If your certificate was revoked, delete the certificate from your Keychain, then follow the "Obtaining your iPhone Development Certificate" or "Obtaining your iPhone Distribution Certificate" section in the iPhone Developer Program Portal User Guide to generate a new certificate.
  4. Make sure you create a backup of your private key. The steps for doing this are described in the iPhone Developer Program Portal User Guide, under "Saving your Private Key and Transferring to other Systems".
  5. If you have the iPhone Developer (or iPhone Distribution) certificate and its associated private key, the Apple WWDR Intermediate certificate is installed, and your certificate is valid, confirm that Online Certificate Status Protocol (OCSP) and Certificate Revocation List (CRL) are set to "Off" in Keychain Access > Preferences > Certificates.
  6. if you still getting problem then contact support apple community.

Not able to start Genymotion device

try to clear the cache in genymotion Setting -> Misc -> Clear cache.

Check this image

maybe it will solve the problem.

How to respond to clicks on a checkbox in an AngularJS directive?

I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:

<input type="checkbox" ng-model="entity.isChecked">

Whenever the user checks or unchecks the checkbox the entity.isChecked value will change too.

If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.

When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners array. The listeners in this array get called after the model value has been set, avoiding this problem).

<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">

... and in the controller ...

var model = {};
$scope.model = model;

// This property is bound to the checkbox in the table header
model.allItemsSelected = false;

// Fired when an entity in the table is checked
$scope.selectEntity = function () {
    // If any entity is not checked, then uncheck the "allItemsSelected" checkbox
    for (var i = 0; i < model.entities.length; i++) {
        if (!model.entities[i].isChecked) {
            model.allItemsSelected = false;
            return;
        }
    }

    // ... otherwise ensure that the "allItemsSelected" checkbox is checked
    model.allItemsSelected = true;
};

Similarly, the "Check All" checkbox in the header:

<th>
    <input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>

... and ...

// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
    // Loop through all the entities and set their isChecked property
    for (var i = 0; i < model.entities.length; i++) {
        model.entities[i].isChecked = model.allItemsSelected;
    }
};

CSS

What is the best way to... add a CSS class to the <tr> containing the entity to reflect its selected state?

If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr> element to dynamically add or remove the class whenever the entity property changes:

<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">

See the full Plunker here.

Vue.js img src concatenate variable and text

You can't use curlies (moustache tags) in attributes. Use the following to concat data:

<img v-bind:src="imgPreUrl + 'img/logo.png'">

Or the short version:

<img :src="imgPreUrl + 'img/logo.png'">

Read more on dynamic attributes in the Vue docs.

Portable way to check if directory exists [Windows/Linux, C]

Use boost::filesystem, that will give you a portable way of doing those kinds of things and abstract away all ugly details for you.

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

While passing string constants to functions write it as:

void setpart(const char name[]);

setpart("Hello");

instead of const char name[], you could also write const char \*name

It worked for me to remove this error:

[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]

Show DialogFragment with animation growing from a point

Add this code on values anim

 <scale
    android:duration="@android:integer/config_longAnimTime"
    android:fromXScale="0.2"
    android:fromYScale="0.2"
    android:toXScale="1.0"
    android:toYScale="1.0"
    android:pivotX="50%"
    android:pivotY="50%"/>
<alpha
    android:fromAlpha="0.1"
    android:toAlpha="1.0"
    android:duration="@android:integer/config_longAnimTime"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>

call on styles.xml

<style name="DialogScale">
    <item name="android:windowEnterAnimation">@anim/scale_in</item>
    <item name="android:windowExitAnimation">@anim/scale_out</item>
</style>

On java code: set Onclick

public void onClick(View v) {
        fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
      //  Dialogs.fab_onclick(R.style.DialogScale, "Scale");

    }

setup on method:

alertDialog.getWindow().getAttributes().windowAnimations = type;

How to avoid "RuntimeError: dictionary changed size during iteration" error?

For situations like this, i like to make a deep copy and loop through that copy while modifying the original dict.

If the lookup field is within a list, you can enumerate in the for loop of the list and then specify the position as index to access the field in the original dict.

Android toolbar center title and custom font

I spent several days searching for a universal solution. My toolbar working with android menu and nav icon.

At first, you need create custom toolbar class. This class must have calculate title centered positions (paddings):

    class CenteredToolbar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : Toolbar(context, attrs, defStyleAttr) {

    init {
        addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
            override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
                val titleTextView = findViewById<TextView>(R.id.centerTitle)

                val x = titleTextView.x.toInt()
                val x2 = x + titleTextView.width

                val fullWidth = width
                val fullCenter = fullWidth / 2

                val offsetLeft = Math.abs(fullCenter - x)
                val offsetRight = Math.abs(x2 - fullCenter)
                val differOffset = Math.abs(offsetLeft - offsetRight)

                if (offsetLeft > offsetRight) {
                    titleTextView.setPadding(differOffset, 0, 0, 0)
                } else if (offsetRight > offsetLeft) {
                    titleTextView.setPadding(0, 0, differOffset, 0)
                }

                removeOnLayoutChangeListener(this)
            }
        })
    }

    override fun setTitle(resId: Int) = getTitleView().setText(resId)

    override fun setTitle(title: CharSequence?) = getTitleView().setText(title)

    fun getTitleView(): TextView = findViewById(R.id.centerTitle)

}

Secondly, you need create layout toolbar:

<CenteredToolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar">

    <TextView
        android:id="@+id/centerTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</CenteredToolbar>

That's all

Determining if an Object is of primitive type

Get ahold of BeanUtils from Spring http://static.springsource.org/spring/docs/3.0.x/javadoc-api/

Probably the Apache variation (commons beans) has similar functionality.

What is the difference between C and embedded C?

Embedded environment, sometime, there is no MMU, less memory, less storage space. In C programming level, almost same, cross compiler do their job.

Using OpenSSL what does "unable to write 'random state'" mean?

One other issue on the Windows platform, make sure you are running your command prompt as an Administrative User!

I don't know how many times this has bitten me...

libaio.so.1: cannot open shared object file

I'm having a similar issue.

I found

conda install pyodbc

is wrong!

when I use

apt-get install python-pyodbc

I solved this problem?

Make child div stretch across width of page

Since position: absolute; and viewport width were no options in my special case, there is another quick solution to solve the problem. The only condition is, that overflow in x-direction is not necessary for your website.

You can define negative margins for your element:

#help_panel {
    margin-left: -9999px;
    margin-right: -9999px;
}

But since we get overflow doing this, we have to avoid overflow in x-direction globally e.g. for body:

body {
    overflow-x: hidden;
}

You can set padding to choose the size of your content.

Note that this solution does not bring 100% width for content, but it is helpful in cases where you need e.g. a background color which has full width with a content still depending on container.

Do checkbox inputs only post data if they're checked?

None of the above answers satisfied me. I found the best solution is to include a hidden input before each checkbox input with the same name.

<input type="hidden" name="foo[]" value="off"/>

<input type="checkbox" name="foo[]"/>

Then on the server side, using a little algorithm you can get something more like HTML should provide.

function checkboxHack(array $checkbox_input): array
{
    $foo = [];
    foreach($checkbox_input as $value) {
        if($value === 'on') {
            array_pop($foo);
        }
        $foo[] = $value;
    }
    return $foo;
}

This will be the raw input

array (
    0 => 'off',
    1 => 'on',
    2 => 'off',
    3 => 'off',
    4 => 'on',
    5 => 'off',
    6 => 'on',
),

And the function will return

array (
    0 => 'on',
    1 => 'off',
    2 => 'on',
    3 => 'on',
)  

How to apply Hovering on html area tag?

What I did was to create a canvas element that I then position in front of the image map. Then, whenever an area is moused-over, I call a func that gets the coord string for that shape and the shape-type. If it's a poly I use the coords to draw an outline on the canvas. If it's a rect I draw a rect outline. You could easily add code to deal with circles.

You could also set the opacity of the canvas to less than 100% before filling the poly/rect/circle. You could also change the reliance on a global for the canvas's context - this would mean you could deal with more than 1 image-map on the same page.

<!DOCTYPE html>
<html>
<head>
<script>

// stores the device context of the canvas we use to draw the outlines
// initialized in myInit, used in myHover and myLeave
var hdc;

// shorthand func
function byId(e){return document.getElementById(e);}

// takes a string that contains coords eg - "227,307,261,309, 339,354, 328,371, 240,331"
// draws a line from each co-ord pair to the next - assumes starting point needs to be repeated as ending point.
function drawPoly(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var i, n;
    n = mCoords.length;

    hdc.beginPath();
    hdc.moveTo(mCoords[0], mCoords[1]);
    for (i=2; i<n; i+=2)
    {
        hdc.lineTo(mCoords[i], mCoords[i+1]);
    }
    hdc.lineTo(mCoords[0], mCoords[1]);
    hdc.stroke();
}

function drawRect(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var top, left, bot, right;
    left = mCoords[0];
    top = mCoords[1];
    right = mCoords[2];
    bot = mCoords[3];
    hdc.strokeRect(left,top,right-left,bot-top); 
}

function myHover(element)
{
    var hoveredElement = element;
    var coordStr = element.getAttribute('coords');
    var areaType = element.getAttribute('shape');

    switch (areaType)
    {
        case 'polygon':
        case 'poly':
            drawPoly(coordStr);
            break;

        case 'rect':
            drawRect(coordStr);
    }
}

function myLeave()
{
    var canvas = byId('myCanvas');
    hdc.clearRect(0, 0, canvas.width, canvas.height);
}

function myInit()
{
    // get the target image
    var img = byId('img-imgmap201293016112');

    var x,y, w,h;

    // get it's position and width+height
    x = img.offsetLeft;
    y = img.offsetTop;
    w = img.clientWidth;
    h = img.clientHeight;

    // move the canvas, so it's contained by the same parent as the image
    var imgParent = img.parentNode;
    var can = byId('myCanvas');
    imgParent.appendChild(can);

    // place the canvas in front of the image
    can.style.zIndex = 1;

    // position it over the image
    can.style.left = x+'px';
    can.style.top = y+'px';

    // make same size as the image
    can.setAttribute('width', w+'px');
    can.setAttribute('height', h+'px');

    // get it's context
    hdc = can.getContext('2d');

    // set the 'default' values for the colour/width of fill/stroke operations
    hdc.fillStyle = 'red';
    hdc.strokeStyle = 'red';
    hdc.lineWidth = 2;
}
</script>

<style>
body
{
    background-color: gray;
}
canvas
{
    pointer-events: none;       /* make the canvas transparent to the mouse - needed since canvas is position infront of image */
    position: absolute;
}
</style>

<title></title>
</head>
<body onload='myInit()'>
    <canvas id='myCanvas'></canvas>     <!-- gets re-positioned in myInit(); -->
<center>
<img src='http://dailyaeen.com.pk/epaper/wp-content/uploads/2012/09/27+Sep+2012-1.jpg?1349003469874' usemap='#imgmap_css_container_imgmap201293016112' class='imgmap_css_container' title='imgmap201293016112' alt='imgmap201293016112' id='img-imgmap201293016112' />
<map id='imgmap201293016112' name='imgmap_css_container_imgmap201293016112'>
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="2,0,604,-3,611,-3,611,166,346,165,345,130,-2,130,-2,124,1,128,1,126" href="" alt="imgmap201293016112-0" title="imgmap201293016112-0" class="imgmap201293016112-area" id="imgmap201293016112-area-0" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,131,341,213" href="" alt="imgmap201293016112-1" title="imgmap201293016112-1" class="imgmap201293016112-area" id="imgmap201293016112-area-1" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,166,614,241" href="" alt="imgmap201293016112-2" title="imgmap201293016112-2" class="imgmap201293016112-area" id="imgmap201293016112-area-2" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,242,344,239,345,496,574,495,575,435,917,433" href="" alt="imgmap201293016112-3" title="imgmap201293016112-3" class="imgmap201293016112-area" id="imgmap201293016112-area-3" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,416,341,494" href="" alt="imgmap201293016112-4" title="imgmap201293016112-4" class="imgmap201293016112-area" id="imgmap201293016112-area-4" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,215,341,410" href="" alt="imgmap201293016112-5" title="imgmap201293016112-5" class="imgmap201293016112-area" id="imgmap201293016112-area-5" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="916,533,916,436,578,436,576,495,806,496,807,535" href="" alt="imgmap201293016112-6" title="imgmap201293016112-6" class="imgmap201293016112-area" id="imgmap201293016112-area-6" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="805,536,918,614" href="" alt="imgmap201293016112-7" title="imgmap201293016112-7" class="imgmap201293016112-area" id="imgmap201293016112-area-7" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,494,803,616" href="" alt="imgmap201293016112-8" title="imgmap201293016112-8" class="imgmap201293016112-area" id="imgmap201293016112-area-8" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,497,223,616" href="" alt="imgmap201293016112-9" title="imgmap201293016112-9" class="imgmap201293016112-area" id="imgmap201293016112-area-9" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,494,456,614" href="" alt="imgmap201293016112-10" title="imgmap201293016112-10" class="imgmap201293016112-area" id="imgmap201293016112-area-10" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,935,572,1082" href="" alt="imgmap201293016112-11" title="imgmap201293016112-11" class="imgmap201293016112-area" id="imgmap201293016112-area-11" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,617,457,760" href="" alt="imgmap201293016112-12" title="imgmap201293016112-12" class="imgmap201293016112-area" id="imgmap201293016112-area-12" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,760,577,847" href="" alt="imgmap201293016112-13" title="imgmap201293016112-13" class="imgmap201293016112-area" id="imgmap201293016112-area-13" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,759,344,906" href="" alt="imgmap201293016112-14" title="imgmap201293016112-14" class="imgmap201293016112-area" id="imgmap201293016112-area-14" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,850,571,935" href="" alt="imgmap201293016112-15" title="imgmap201293016112-15" class="imgmap201293016112-area" id="imgmap201293016112-area-15" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="578,761,915,865" href="" alt="imgmap201293016112-16" title="imgmap201293016112-16" class="imgmap201293016112-area" id="imgmap201293016112-area-16" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1017,226,1085" href="" alt="imgmap201293016112-17" title="imgmap201293016112-17" class="imgmap201293016112-area" id="imgmap201293016112-area-17" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,908,342,1017" href="" alt="imgmap201293016112-18" title="imgmap201293016112-18" class="imgmap201293016112-area" id="imgmap201293016112-area-18" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="229,1010,342,1084" href="" alt="imgmap201293016112-19" title="imgmap201293016112-19" class="imgmap201293016112-area" id="imgmap201293016112-area-19" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1086,340,1206" href="" alt="imgmap201293016112-20" title="imgmap201293016112-20" class="imgmap201293016112-area" id="imgmap201293016112-area-20" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1209,224,1290" href="" alt="imgmap201293016112-21" title="imgmap201293016112-21" class="imgmap201293016112-area" id="imgmap201293016112-area-21" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1290,225,1432" href="" alt="imgmap201293016112-22" title="imgmap201293016112-22" class="imgmap201293016112-area" id="imgmap201293016112-area-22" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1432,340,1517" href="" alt="imgmap201293016112-23" title="imgmap201293016112-23" class="imgmap201293016112-area" id="imgmap201293016112-area-23" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,1432,686,1517" href="" alt="imgmap201293016112-24" title="imgmap201293016112-24" class="imgmap201293016112-area" id="imgmap201293016112-area-24" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,1266,686,1429" href="" alt="imgmap201293016112-25" title="imgmap201293016112-25" class="imgmap201293016112-area" id="imgmap201293016112-area-25" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1365,455,1430" href="" alt="imgmap201293016112-26" title="imgmap201293016112-26" class="imgmap201293016112-area" id="imgmap201293016112-area-26" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="231,1291,457,1360" href="" alt="imgmap201293016112-27" title="imgmap201293016112-27" class="imgmap201293016112-area" id="imgmap201293016112-area-27" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1210,342,1289" href="" alt="imgmap201293016112-28" title="imgmap201293016112-28" class="imgmap201293016112-area" id="imgmap201293016112-area-28" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="692,928,916,1016" href="" alt="imgmap201293016112-29" title="imgmap201293016112-29" class="imgmap201293016112-area" id="imgmap201293016112-area-29" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="460,616,916,759" href="" alt="imgmap201293016112-30" title="imgmap201293016112-30" class="imgmap201293016112-area" id="imgmap201293016112-area-30" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1316,917,1518" href="" alt="imgmap201293016112-31" title="imgmap201293016112-31" class="imgmap201293016112-area" id="imgmap201293016112-area-31" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="344,1150,572,1219" href="" alt="imgmap201293016112-32" title="imgmap201293016112-32" class="imgmap201293016112-area" id="imgmap201293016112-area-32" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1015,916,1171" href="" alt="imgmap201293016112-33" title="imgmap201293016112-33" class="imgmap201293016112-area" id="imgmap201293016112-area-33" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,955,686,1032" href="" alt="imgmap201293016112-34" title="imgmap201293016112-34" class="imgmap201293016112-area" id="imgmap201293016112-area-34" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,1036,687,1101" href="" alt="imgmap201293016112-35" title="imgmap201293016112-35" class="imgmap201293016112-area" id="imgmap201293016112-area-35" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="576,1104,689,1172" href="" alt="imgmap201293016112-36" title="imgmap201293016112-36" class="imgmap201293016112-area" id="imgmap201293016112-area-36" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="691,1232,918,1313" href="" alt="imgmap201293016112-37" title="imgmap201293016112-37" class="imgmap201293016112-area" id="imgmap201293016112-area-37" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="341,1085,573,1151" href="" alt="imgmap201293016112-38" title="imgmap201293016112-38" class="imgmap201293016112-area" id="imgmap201293016112-area-38" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,868,917,925,688,927,688,955,576,955,574,867,572,864" href="" alt="imgmap201293016112-39" title="imgmap201293016112-39" class="imgmap201293016112-area" id="imgmap201293016112-area-39" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="919,1173,917,1231,688,1231,688,1266,574,1267,576,1175,576,1175" href="" alt="imgmap201293016112-40" title="imgmap201293016112-40" class="imgmap201293016112-area" id="imgmap201293016112-area-40" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="572,1222,572,1265,459,1265,458,1289,339,1290,344,1225" href="" alt="imgmap201293016112-41" title="imgmap201293016112-41" class="imgmap201293016112-area" id="imgmap201293016112-area-41" />
</map>
</center>

</body>
</html>

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I have a case where I am transforming a legacy DB2 z/os database timestamp (formatted as: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") into a SqlServer 2016 datetime2 (formatted as: "yyyy-MM-dd HH:mm:ss.SSS) field that is handled by our Spring/Hibernate Entity Manager instance (in this case, the OldRevision Table). In the Class, I define the date as the java.util type, and write the setter and getter in the normal way. Then, When handling the data, the code I have handling the data related to this question looks like this:

OldRevision revision = new OldRevision();
String oldRevisionDateString= oldRevisionData.getString("originalRevisionDate", "");
Date oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
oldDateFormat.parse(oldRevisionDateString);
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Date finalFormattedDate= newDateFormat.parse(newDateFormat.format(oldDateFormat));
revision.setOriginalRevisionDate(finalFormattedDate);
em.persist(revision);

A simpler way to do the same case is:

SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
newDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
revision.setOriginalRevisionDate(
        newDateFormat.parse(newDateFormat.format(
                new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ")
                        .parse(rs.getString("originalRevisionDate", "")))));

What causes "Unable to access jarfile" error?

This is permission issue, see if the directory is under your User. That's why is working in another folder!

Enum ToString with user friendly strings

In case you just want to add a whitespace between the words, it is as simple as

string res = Regex.Replace(PublishStatusses.NotCompleted, "[A-Z]", " $0").Trim();

Is 'bool' a basic datatype in C++?

C++ does lots of automatic casting for you - that is, if you have a variable of type bool and pass it to something expecting an int, it will make it into an int for you - 0 for false and 1 for true.

I don't have my standard around to see if this is guaranteed, but every compiler I've used does this (so one can assume it will always work).

However, relying on this conversion is a bad idea. Code can stop compiling if a new method is added that overloads the int signature, etc.

Fill background color left to right CSS

A single css code on hover can do the trick: box-shadow: inset 100px 0 0 0 #e0e0e0;

A complete demo can be found in my fiddle:

https://jsfiddle.net/shuvamallick/3o0h5oka/

How can I read the client's machine/computer name from the browser?

It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.

Like some one answered in one of the previous question today.

I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)

You cannot do it using asp.net as well.

Understanding ibeacon distancing

It's possible, but it depends on the power output of the beacon you're receiving, other rf sources nearby, obstacles and other environmental factors. Best thing to do is try it out in the environment you're interested in.

How do you get the footer to stay at the bottom of a Web page?

Use CSS vh units!

Probably the most obvious and non-hacky way to go about a sticky footer would be to make use of the new css viewport units.

Take for example the following simple markup:

<header>header goes here</header>
<div class="content">This page has little content</div>
<footer>This is my footer</footer>

If the header is say 80px high and the footer is 40px high, then we can make our sticky footer with one single rule on the content div:

.content {
    min-height: calc(100vh - 120px);
    /* 80px header + 40px footer = 120px  */
}

Which means: let the height of the content div be at least 100% of the viewport height minus the combined heights of the header and footer.

That's it.

_x000D_
_x000D_
* {_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
}_x000D_
.content {_x000D_
    min-height: calc(100vh - 120px);_x000D_
    /* 80px header + 40px footer = 120px  */_x000D_
    background: pink;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">This page has little content</div>_x000D_
<footer>This is my footer</footer>
_x000D_
_x000D_
_x000D_

... and here's how the same code works with lots of content in the content div:

_x000D_
_x000D_
* {_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
}_x000D_
.content {_x000D_
    min-height: calc(100vh - 120px);_x000D_
    /* 80px header + 40px footer = 120px  */_x000D_
    background: pink;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum._x000D_
</div>_x000D_
<footer>_x000D_
    This is my footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

NB:

1) The height of the header and footer must be known

2) Old versions of IE (IE8-) and Android (4.4-) don't support viewport units. (caniuse)

3) Once upon a time webkit had a problem with viewport units within a calc rule. This has indeed been fixed (see here) so there's no problem there. However if you're looking to avoid using calc for some reason you can get around that using negative margins and padding with box-sizing -

Like so:

_x000D_
_x000D_
* {_x000D_
    margin:0;padding:0;_x000D_
}_x000D_
header {_x000D_
    background: yellow;_x000D_
    height: 80px;_x000D_
    position:relative;_x000D_
}_x000D_
.content {_x000D_
    min-height: 100vh;_x000D_
    background: pink;_x000D_
    margin: -80px 0 -40px;_x000D_
    padding: 80px 0 40px;_x000D_
    box-sizing:border-box;_x000D_
}_x000D_
footer {_x000D_
    height: 40px;_x000D_
    background: aqua;_x000D_
}
_x000D_
<header>header goes here</header>_x000D_
<div class="content">Lorem ipsum _x000D_
</div>_x000D_
<footer>_x000D_
    This is my footer_x000D_
</footer>
_x000D_
_x000D_
_x000D_

PHP append one array to another (not array_push or +)

Why not use

$appended = array_merge($a,$b); 

Why don't you want to use this, the correct, built-in method.

How do I load an org.w3c.dom.Document from XML in a string?

Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.

private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);

public static Document loadXMLFrom(String xml) throws Exception {
        InputSource is= new InputSource(new StringReader(xml));
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = null;
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc;
    }

How to set a Timer in Java?

Use this

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception

Regex matching in a Bash if statement

There are a couple of important things to know about bash's [[ ]] construction. The first:

Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.

The second thing:

An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.

Consequently, $v on either side of the =~ will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.

So if you write: [[ $x =~ [$0-9a-zA-Z] ]], the $0 inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0 ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]], then the right-hand side will be treated as an ordinary string, not a regex (and $0 will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]

Similarly, the expression between the [[ and ]] is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]. Other characters similarly need to be escaped, like #, which would start a comment if not quoted. Of course, you can put the pattern into a variable:

pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...

For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:

# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...

Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:

valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...

! negates the test, turning it into a "does not match" operator, and a [^...] regex character class means "any character other than ...".

The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ] into $valid, even if $valid were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ] in a character class, it needs to go at the beginning. - can go at the beginning or the end, so if you need both ] and -, you need to start with ] and end with -, leading to the regex "I know what I'm doing" emoticon: [][-])

How do I count columns of a table

To count the columns of your table precisely, you can get form information_schema.columns with passing your desired Database(Schema) Name and Table Name.


Reference the following Code:

SELECT count(*)
FROM information_schema.columns
WHERE table_schema = 'myDB'  
AND table_name = 'table1';

Difference between webdriver.get() and webdriver.navigate()

For what it's worth, from my IE9 testing, it looks like there's a difference for URLs that contain a hashbang (a single page app, in my case):

http://www.example.com#page

The driver.get("http://www.example.com#anotherpage") method is handled by the browser as a fragment identifier and JavaScript variables are retained from the previous URL.

While, the navigate().to("http://www.example.com#anotherpage") method is handled by the browser as a address/location/URL bar input and JavaScript variables are not retained from the previous URL.

Regex remove all special characters except numbers?

To remove the special characters, try

var name = name.replace(/[!@#$%^&*]/g, "");

How to get SQL from Hibernate Criteria API (*not* for logging)

Here is a method I used and worked for me

public static String toSql(Session session, Criteria criteria){
    String sql="";
    Object[] parameters = null;
    try{
        CriteriaImpl c = (CriteriaImpl) criteria;
        SessionImpl s = (SessionImpl)c.getSession();
        SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
        String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
        CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]), factory, c, implementors[0], s.getEnabledFilters());
        Field f = OuterJoinLoader.class.getDeclaredField("sql");
        f.setAccessible(true);
        sql = (String)f.get(loader);
        Field fp = CriteriaLoader.class.getDeclaredField("traslator");
        fp.setAccessible(true);
        CriteriaQueryTranslator translator = (CriteriaQueryTranslator) fp.get(loader);
        parameters = translator.getQueryParameters().getPositionalParameterValues();
    }
    catch(Exception e){
        throw new RuntimeException(e);
    }
    if (sql !=null){
        int fromPosition = sql.indexOf(" from ");
        sql = "SELECT * "+ sql.substring(fromPosition);

        if (parameters!=null && parameters.length>0){
            for (Object val : parameters) {
                String value="%";
                if(val instanceof Boolean){
                    value = ((Boolean)val)?"1":"0";
                }else if (val instanceof String){
                    value = "'"+val+"'";
                }
                sql = sql.replaceFirst("\\?", value);
            }
        }
    }
    return sql.replaceAll("left outer join", "\nleft outer join").replace(" and ", "\nand ").replace(" on ", "\non ");
}

Parse JSON from HttpURLConnection object

This function will be used get the data from url in form of HttpResponse object.

public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}

Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.

String jsonString     =     
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
                    jsonElementForJavaObject, JsonJavaModel.class);

This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:

public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {

@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
                                 JsonDeserializationContext arg2) throws    JsonParseException {
    final JsonJavaModel jsonJavaModel= new JsonJavaModel();
    JsonObject object = json.getAsJsonObject();

    try {
     jsonJavaModel.content = object.get("Content").getAsString()
     jsonJavaModel.title = object.get("Title").getAsString()

    } catch (Exception e) {

        e.printStackTrace();
    }
    return jsonJavaModel;
}

Include Gson library and org.apache.http.util.EntityUtils;

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The <em> element - from W3C (HTML5 reference)

YES! There is a clear difference.

The <em> element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em> elements.

<strong>  =  important content
<em>      =  stress emphasis of its contents

The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.

Note!

  1. The <em> element also isnt intended to convey importance; for that purpose, the <strong> element is more appropriate.

  2. The <em> element isn't a generic "italics" element. Sometimes, text is intended to stand out from the rest of the paragraph, as if it was in a different mood or voice. For this, the i element is more appropriate.

Reference (examples): See W3C Reference

Stop absolutely positioned div from overlapping text

You should set z-index to absolutely positioned div that is greater than to relative div.

Something like that

<div style="position: relative; width:600px; z-index: 10;">
    <p>Content of unknown length</p>
    <div>Content of unknown height</div>
    <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px; z-index: 20;"></div>
</div>

z-index sets layers positioning in depth of page.

Or you may use floating to show all text of unkown length. But in this case you could not absolutely position your div

<div style="position: relative; width:600px;">
  <div class="btn" style="float: right; width: 200px; height: 100px;"></div>
  <p>Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length Content of unknown length</p>
  <div>Content of unknown height</div>
  <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>
</div>?

How to change language of app when user selects language?

It's excerpt for the webpage: http://android.programmerguru.com/android-localization-at-runtime/

It's simple to change the language of your app upon user selects it from list of languages. Have a method like below which accepts the locale as String (like 'en' for English, 'hi' for hindi), configure the locale for your App and refresh your current activity to reflect the change in language. The locale you applied will not be changed until you manually change it again.

public void setLocale(String lang) { 
    Locale myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, AndroidLocalize.class); 
    finish();
    startActivity(refresh); 
} 

Make sure you imported following packages:

import java.util.Locale; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Intent; 
import android.content.res.Configuration; 
import android.content.res.Resources; 
import android.util.DisplayMetrics; 

add in manifest to activity android:configChanges="locale|orientation"

How to prevent colliders from passing through each other?

Old Question but maybe it helps someone.

Go to Project settings > Time and Try dividing the fixed timestep and maximum allowed timestep by two or by four.

I had the problem that my player was able to squeeze through openings smaller than the players collider and that solved it. It also helps with stopping fast moving objects.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

upgraded Android Studio from 3.2.1 to 3.3 and the problem disappeared

How to use ArrayList.addAll()?

Collections.addAll is what you want.

Collections.addAll(myArrayList, '+', '-', '*', '^');

Another option is to pass the list into the constructor using Arrays.asList like this:

List<Character> myArrayList = new ArrayList<Character>(Arrays.asList('+', '-', '*', '^'));

If, however, you are good with the arrayList being fixed-length, you can go with the creation as simple as list = Arrays.asList(...). Arrays.asList specification states that it returns a fixed-length list which acts as a bridge to the passed array, which could be not what you need.