Programs & Examples On #Driveinfo

SQLite with encryption/password protection

Well, SEE is expensive. However SQLite has interface built-in for encryption (Pager). This means, that on top of existing code one can easily develop some encryption mechanism, does not have to be AES. Anything really. Please see my post here: https://stackoverflow.com/a/49161716/9418360

You need to define SQLITE_HAS_CODEC=1 to enable Pager encryption. Sample code below (original SQLite source):

#ifdef SQLITE_HAS_CODEC
/*
** This function is called by the wal module when writing page content
** into the log file.
**
** This function returns a pointer to a buffer containing the encrypted
** page content. If a malloc fails, this function may return NULL.
*/
SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  void *aData = 0;
  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  return aData;
}
#endif

There is a commercial version in C language for SQLite encryption using AES256 - it can also work with PHP, but it needs to be compiled with PHP and SQLite extension. It de/encrypts SQLite database file on the fly, file contents are always encrypted. Very useful.

http://www.iqx7.com/products/sqlite-encryption

How to restrict SSH users to a predefined set of commands after login?

You should acquire `rssh', the restricted shell

You can follow the restriction guides mentioned above, they're all rather self-explanatory, and simple to follow. Understand the terms `chroot jail', and how to effectively implement sshd/terminal configurations, and so on.

Being as most of your users access your terminals via sshd, you should also probably look into sshd_conifg, the SSH daemon configuration file, to apply certain restrictions via SSH. Be careful, however. Understand properly what you try to implement, for the ramifications of incorrect configurations are probably rather dire.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

Don't think anyone mentioned the overhead in exception handling - takes additional resources to load up and process the exception so unless its a true app killing or process stopping event (going forward would cause more harm than good) I would opt for passing back a value the calling environment could interpret as it sees fit.

TypeScript getting error TS2304: cannot find name ' require'

Sometime missing "jasmine" from tsconfig.json may cause this error. (TypeScript 2.X)

So add

"types": [
  "node",
  "jasmine"
]

to your tsconfig.json file.

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

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

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

How to convert .pem into .key?

CA's don't ask for your private keys! They only asks for CSR to issue a certificate for you.

If they have your private key, it's possible that your SSL certificate will be compromised and end up being revoked.

Your .key file is generated during CSR generation and, most probably, it's somewhere on your PC where you generated the CSR.

That's why private key is called "Private" - because nobody can have that file except you.

Difference between two dates in years, months, days in JavaScript

I do it this way. Precise? Maybe or maybe not. Try it

<html>
  <head>
    <title> Age Calculator</title>
  </head>

  <input type="date" id="startDate" value="2000-01-01">
  <input type="date" id="endDate"  value="2020-01-01">
  <button onclick="getAge(new Date(document.getElementById('startDate').value), new Date(document.getElementById('endDate').value))">Check Age</button>
  <script>
    function getAge (startDate, endDate) {
      var diff = endDate-startDate
      var age = new Date(new Date("0000-01-01").getTime()+diff)
      var years = age.getFullYear()
      var months = age.getMonth()
      var days = age.getDate()
      console.log(years,"years",months,"months",days-1,"days")
      return (years+"years "+ months+ "months"+ days,"days")
    }
  </script>
</html>

When is a language considered a scripting language?

I always looked at scripting languages as a means to communicate with some sort of application or program. In contrast, a language which is compiled actually creates the program itself.

Now keep in mind that a scripting language usually adds on to or modifies the program that was initially created with a language that was compiled. Thus, it can certainly be part of the larger picture but the initial binaries are first created with a language that is compiled.

So I could create a scripting language which lets users perform various actions or customize my program. My program would interpret the scripted code and in turn call some kind of function. This is just a basic example. It just gives you a way to dynamically call routines within the program.

My program would have to parse the scripted code (you could refer to these as commands) and execute whatever action was intended in real time.

I see this question was already answered several times but I thought I would add my way of looking at things into the mix. Granted, some folks may disagree with this answer but this way of thinking has always helped me.

Angularjs simple file download causes router to redirect

https://docs.angularjs.org/guide/$location#html-link-rewriting

In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.

  • Links that contain target element Example:
    <a href="/ext/link?a=b" target="_self">link</a>

  • Absolute links that go to a different domain Example:
    <a href="http://angularjs.org/">link</a>

  • Links starting with '/' that lead to a different base path when base is defined Example:
    <a href="/not-my-base/link">link</a>

So in your case, you should add a target attribute like so...

<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">

Filter dataframe rows if value in column is in a set list of values

Use the isin method:

rpt[rpt['STK_ID'].isin(stk_list)]

Is there an upside down caret character?

I did subscript capital & bolded V. It works perfectly (although it takes some effort, if it needs to be done repetitively)

Syntax:

<sub><strong>v</strong></sub>

Output:
v

Can't fix Unsupported major.minor version 52.0 even after fixing compatibility

First of all thank you for all above answers. However, I use Intellij Idea for daily basis. So, I hope my answer will help others.

Run your favourite terminal or command line. Then check your java version by running command

java -version

Then in Intellij press

Ctrl+Alt+Shift+S

in the

Project Settings

tab under

Project SDK

choose appropriate java version. Lastly, rerun your code.

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

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

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

ATTENTION ::

-- because of poorly made caching system, in Atom loss of data occurs often when using big files.

It has been proven numerous times.

JavaScript math, round to two decimal places

The best and simple solution I found is

function round(value, decimals) {
 return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}   
round(1.005, 2); // 1.01

How to check if text fields are empty on form submit using jQuery?

A simple solution would be something like this

$( "form" ).on( "submit", function() { 

   var has_empty = false;

   $(this).find( 'input[type!="hidden"]' ).each(function () {

      if ( ! $(this).val() ) { has_empty = true; return false; }
   });

   if ( has_empty ) { return false; }
});

Note: The jQuery.on() method is only available in jQuery version 1.7+, but it is now the preferred method of attaching event handlers.

This code loops through all of the inputs in the form and prevents form submission by returning false if any of them have no value. Note that it doesn't display any kind of message to the user about why the form failed to submit (I would strongly recommend adding one).

Or, you could look at the jQuery validate plugin. It does this and a lot more.

NB: This type of technique should always be used in conjunction with server side validation.

Python os.path.join() on a list

This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.

import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]

reduce is builtin in Python 2.x. In Python 3.x it has been moved to itertools However the accepted the answer is better.

This has been answered below but answering if you have a list of items that needs to be joined.

How to read a list of files from a folder using PHP?

There is also a really simple way to do this with the help of the RecursiveTreeIterator class, answered here: https://stackoverflow.com/a/37548504/2032235

Delete last char of string

Additional to sll's solution: It's better to trim the string in case there are some blank(s) at the end.

strgroupids = strgroupids.Remove(strgroupids.Trim().Length - 1);

How to tell which commit a tag points to in Git?

On my repository, git show-ref TAG shows the tag's hash, not the hash of the commit it points to.

git show-ref --dereference TAG shows, additionally, the commit being pointed at.

Access Google's Traffic Data through a Web Service

It is possible to get traffic data. Below is my implementation in python. The API has some quota & is not fully free, but good enough for small projects

import requests
import time
import json


while True:

    url = "https://maps.googleapis.com/maps/api/distancematrix/json"

    querystring = {"units":"metric","departure_time":str(int(time.time())),"traffic_model":"best_guess","origins":"ITPL,Bangalore","destinations":"Tin Factory,Bangalore","key":"GetYourKeyHere"}

    headers = {
        'cache-control': "no-cache",
        'postman-token': "something"
        }

    response = requests.request("GET", url, headers=headers, params=querystring)
    d = json.loads(response.text)
    print("On", time.strftime("%I:%M:%S"),"time duration is",d['rows'][0]['elements'][0]['duration']['text'], " & traffic time is ",d['rows'][0]['elements'][0]['duration_in_traffic']['text'])
    time.sleep(1800)
    print(response.text)

Response is :-

{
    "destination_addresses": [
        "Tin Factory, Swamy Vivekananda Rd, Krishna Reddy Industrial Estate, Dooravani Nagar, Bengaluru, Karnataka 560016, India"
    ],
    "origin_addresses": [
        "Whitefield Main Rd, Pattandur Agrahara, Whitefield, Bengaluru, Karnataka 560066, India"
    ],
    "rows": [
        {
            "elements": [
                {
                    "distance": {
                        "text": "10.5 km",
                        "value": 10505
                    },
                    "duration": {
                        "text": "35 mins",
                        "value": 2120
                    },
                    "duration_in_traffic": {
                        "text": "45 mins",
                        "value": 2713
                    },
                    "status": "OK"
                }
            ]
        }
    ],
    "status": "OK"
}

You need to pass "departure_time":str(int(time.time())) is a required query string parameter for traffic information.

Your traffic information would be present in duration_in_traffic.

Refer this documentation for more info.

https://developers.google.com/maps/documentation/distance-matrix/intro#traffic-model

How to change checkbox's border style in CSS?

put it in a div and add border to the div

How to display errors for my MySQLi query?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

 mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));

As a side note I'd say you are at risk of mysql injection, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.

Why should Java 8's Optional not be used in arguments

First of all, if you're using method 3, you can replace those last 14 lines of code with this:

int result = myObject.calculateSomething(p1.orElse(null), p2.orElse(null));

The four variations you wrote are convenience methods. You should only use them when they're more convenient. That's also the best approach. That way, the API is very clear which members are necessary and which aren't. If you don't want to write four methods, you can clarify things by how you name your parameters:

public int calculateSomething(String p1OrNull, BigDecimal p2OrNull)

This way, it's clear that null values are allowed.

Your use of p1.orElse(null) illustrates how verbose our code gets when using Optional, which is part of why I avoid it. Optional was written for functional programming. Streams need it. Your methods should probably never return Optional unless it's necessary to use them in functional programming. There are methods, like Optional.flatMap() method, that requires a reference to a function that returns Optional. Here's its signature:

public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper)

So that's usually the only good reason for writing a method that returns Optional. But even there, it can be avoided. You can pass a getter that doesn't return Optional to a method like flatMap(), by wrapping it in a another method that converts the function to the right type. The wrapper method looks like this:

public static <T, U> Function<? super T, Optional<U>> optFun(Function<T, U> function) {
    return t -> Optional.ofNullable(function.apply(t));
}

So suppose you have a getter like this: String getName()

You can't pass it to flatMap like this:

opt.flatMap(Widget::getName) // Won't work!

But you can pass it like this:

opt.flatMap(optFun(Widget::getName)) // Works great!

Outside of functional programming, Optionals should be avoided.

Brian Goetz said it best when he said this:

The reason Optional was added to Java is because this:

return Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
    .stream()
    .filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
    .filter(m ->  Arrays.equals(m.getParameterTypes(), parameterClasses))
    .filter(m -> Objects.equals(m.getReturnType(), returnType))
    .findFirst()
    .getOrThrow(() -> new InternalError(...));

is cleaner than this:

Method matching =
    Arrays.asList(enclosingInfo.getEnclosingClass().getDeclaredMethods())
    .stream()
    .filter(m -> Objects.equals(m.getName(), enclosingInfo.getName())
    .filter(m ->  Arrays.equals(m.getParameterTypes(), parameterClasses))
    .filter(m -> Objects.equals(m.getReturnType(), returnType))
    .getFirst();
if (matching == null)
  throw new InternalError("Enclosing method not found");
return matching;

Git: can't undo local changes (error: path ... is unmerged)

git checkout origin/[branch] .
git status

// Note dot (.) at the end. And all will be good

How to save an image to localStorage and display it on the next page?

If your images keep getting cropped, here's some code to get the dimensions of the image file before saving to localstorage.

First, I would create some hidden input boxes to hold the width and height values

<input id="file-h" hidden type="text"/>
<input id="file-w" hidden type="text"/>

Then get the dimensions of your file into the input boxes

var _URL = window.URL || window.webkitURL;
$("#file-input").change(function(e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function() {
            $("#file-h").val(this.height);
            $("#file-w").val(this.width);
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);
    }
});

Lastly, change the width and height objects used in the getBase64Image() function by pointing to your input box values

FROM

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

TO

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = $("#file-w").val();
    canvas.height = $("#file-h").val();

Also, you are going to have to maintain a size of about 300kb for all files. There are posts on stackoverflow that cover file size validation using Javascript.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

UPDATE: I've gotten a few upvotes on this lately, so I figured I'd let people know the advice I give below isn't the best. Since I originally started mucking about with doing Entity Framework on old keyless databases, I've come to realize that the best thing you can do BY FAR is do it by reverse code-first. There are a few good articles out there on how to do this. Just follow them, and then when you want to add a key to it, use data annotations to "fake" the key.

For instance, let's say I know my table Orders, while it doesn't have a primary key, is assured to only ever have one order number per customer. Since those are the first two columns on the table, I'd set up the code first classes to look like this:

    [Key, Column(Order = 0)]
    public Int32? OrderNumber { get; set; }

    [Key, Column(Order = 1)]
    public String Customer { get; set; }

By doing this, you're basically faked EF into believing that there's a clustered key composed of OrderNumber and Customer. This will allow you to do inserts, updates, etc on your keyless table.

If you're not too familiar with doing reverse Code First, go and find a good tutorial on Entity Framework Code First. Then go find one on Reverse Code First (which is doing Code First with an existing database). Then just come back here and look at my key advice again. :)

Original Answer:

First: as others have said, the best option is to add a primary key to the table. Full stop. If you can do this, read no further.

But if you can't, or just hate yourself, there's a way to do it without the primary key.

In my case, I was working with a legacy system (originally flat files on a AS400 ported to Access and then ported to T-SQL). So I had to find a way. This is my solution. The following worked for me using Entity Framework 6.0 (the latest on NuGet as of this writing).

  1. Right-click on your .edmx file in the Solution Explorer. Choose "Open With..." and then select "XML (Text) Editor". We're going to be hand-editing the auto-generated code here.

  2. Look for a line like this:
    <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" store:Schema="dbo" store:Name="table_nane">

  3. Remove store:Name="table_name" from the end.

  4. Change store:Schema="whatever" to Schema="whatever"

  5. Look below that line and find the <DefiningQuery> tag. It will have a big ol' select statement in it. Remove the tag and it's contents.

  6. Now your line should look something like this:
    <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" Schema="dbo" />

  7. We have something else to change. Go through your file and find this:
    <EntityType Name="table_name">

  8. Nearby you'll probably see some commented text warning you that it didn't have a primary key identified, so the key has been inferred and the definition is a read-only table/view. You can leave it or delete it. I deleted it.

  9. Below is the <Key> tag. This is what Entity Framework is going to use to do insert/update/deletes. SO MAKE SURE YOU DO THIS RIGHT. The property (or properties) in that tag need to indicate a uniquely identifiable row. For instance, let's say I know my table orders, while it doesn't have a primary key, is assured to only ever have one order number per customer.

So mine looks like:

<EntityType Name="table_name">
              <Key>
                <PropertyRef Name="order_numbers" />
                <PropertyRef Name="customer_name" />
              </Key>

Seriously, don't do this wrong. Let's say that even though there should never be duplicates, somehow two rows get into my system with the same order number and customer name. Whooops! That's what I get for not using a key! So I use Entity Framework to delete one. Because I know the duplicate is the only order put in today, I do this:

var duplicateOrder = myModel.orders.First(x => x.order_date == DateTime.Today);
myModel.orders.Remove(duplicateOrder);

Guess what? I just deleted both the duplicate AND the original! That's because I told Entity Framework that order_number/cutomer_name was my primary key. So when I told it to remove duplicateOrder, what it did in the background was something like:

DELETE FROM orders
WHERE order_number = (duplicateOrder's order number)
AND customer_name = (duplicateOrder's customer name)

And with that warning... you should now be good to go!

JavaScript chop/slice/trim off last character in string

In cases where you want to remove something that is close to the end of a string (in case of variable sized strings) you can combine slice() and substr().

I had a string with markup, dynamically built, with a list of anchor tags separated by comma. The string was something like:

var str = "<a>text 1,</a><a>text 2,</a><a>text 2.3,</a><a>text abc,</a>";

To remove the last comma I did the following:

str = str.slice(0, -5) + str.substr(-4);

Serialize an object to XML

You have to use XmlSerializer for XML serialization. Below is a sample snippet.

 XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
 var subReq = new MyObject();
 var xml = "";

 using(var sww = new StringWriter())
 {
     using(XmlWriter writer = XmlWriter.Create(sww))
     {
         xsSubmit.Serialize(writer, subReq);
         xml = sww.ToString(); // Your XML
     }
 }

How to set root password to null

It's not a good idea to edit mysql database directly.

I prefer the following steps:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY ''; 
mysql> flush privileges;

Transposing a 1D NumPy array

For 1D arrays:

a = np.array([1, 2, 3, 4])
a = a.reshape((-1, 1)) # <--- THIS IS IT

print a
array([[1],
       [2],
       [3],
       [4]])

Once you understand that -1 here means "as many rows as needed", I find this to be the most readable way of "transposing" an array. If your array is of higher dimensionality simply use a.T.

Maintain model of scope when changing between views in AngularJS

You can use $locationChangeStart event to store the previous value in $rootScope or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope.

enter image description here

_x000D_
_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
app.controller("tab1Ctrl", function($scope, $rootScope) {_x000D_
    if ($rootScope.savedScopes) {_x000D_
        for (key in $rootScope.savedScopes) {_x000D_
            $scope[key] = $rootScope.savedScopes[key];_x000D_
        }_x000D_
    }_x000D_
    $scope.$on('$locationChangeStart', function(event, next, current) {_x000D_
        $rootScope.savedScopes = {_x000D_
            name: $scope.name,_x000D_
            age: $scope.age_x000D_
        };_x000D_
    });_x000D_
});_x000D_
app.controller("tab2Ctrl", function($scope) {_x000D_
    $scope.language = "English";_x000D_
});_x000D_
app.config(function($routeProvider) {_x000D_
    $routeProvider_x000D_
        .when("/", {_x000D_
            template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",_x000D_
            controller: "tab1Ctrl"_x000D_
        })_x000D_
        .when("/tab2", {_x000D_
            template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",_x000D_
            controller: "tab2Ctrl"_x000D_
        });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>_x000D_
<body ng-app="myApp">_x000D_
    <a href="#/!">Tab1</a>_x000D_
    <a href="#!tab2">Tab2</a>_x000D_
    <div ng-view></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Signed versus Unsigned Integers

(in answer to the second question) By only using a sign bit (and not 2's complement), you can end up with -0. Not very pretty.

Difference between BYTE and CHAR in column datatypes

I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.

Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).

Remove the string on the beginning of an URL

Another way:

Regex.Replace(urlString, "www.(.+)", "$1");

Responsive web design is working on desktop but not on mobile device

I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.

<meta name="viewport" content="initial-scale=1, maximum-scale=1">

Angular and debounce

DebounceTime in Angular 7 with RxJS v6

Source Link

Demo Link

enter image description here

In HTML Template

<input type="text" #movieSearchInput class="form-control"
            placeholder="Type any movie name" [(ngModel)]="searchTermModel" />

In component

    ....
    ....
    export class AppComponent implements OnInit {

    @ViewChild('movieSearchInput') movieSearchInput: ElementRef;
    apiResponse:any;
    isSearching:boolean;

        constructor(
        private httpClient: HttpClient
        ) {
        this.isSearching = false;
        this.apiResponse = [];
        }

    ngOnInit() {
        fromEvent(this.movieSearchInput.nativeElement, 'keyup').pipe(
        // get value
        map((event: any) => {
            return event.target.value;
        })
        // if character length greater then 2
        ,filter(res => res.length > 2)
        // Time in milliseconds between key events
        ,debounceTime(1000)        
        // If previous query is diffent from current   
        ,distinctUntilChanged()
        // subscription for response
        ).subscribe((text: string) => {
            this.isSearching = true;
            this.searchGetCall(text).subscribe((res)=>{
            console.log('res',res);
            this.isSearching = false;
            this.apiResponse = res;
            },(err)=>{
            this.isSearching = false;
            console.log('error',err);
            });
        });
    }

    searchGetCall(term: string) {
        if (term === '') {
        return of([]);
        }
        return this.httpClient.get('http://www.omdbapi.com/?s=' + term + '&apikey=' + APIKEY,{params: PARAMS.set('search', term)});
    }

    }

Split large string in n-size chunks in JavaScript

My issue with the above solution is that it beark the string into formal size chunks regardless of the position in the sentences.

I think the following a better approach; although it needs some performance tweaking:

 static chunkString(str, length, size,delimiter='\n' ) {
        const result = [];
        for (let i = 0; i < str.length; i++) {
            const lastIndex = _.lastIndexOf(str, delimiter,size + i);
            result.push(str.substr(i, lastIndex - i));
            i = lastIndex;
        }
        return result;
    }

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Any way to declare an array in-line?

You can create a method somewhere

public static <T> T[] toArray(T... ts) {
    return ts;
}

then use it

m(toArray("blah", "hey", "yo"));

for better look.

Using an attribute of the current class instance as a default value for method's parameter

There is much more to it than you think. Consider the defaults to be static (=constant reference pointing to one object) and stored somewhere in the definition; evaluated at method definition time; as part of the class, not the instance. As they are constant, they cannot depend on self.

Here is an example. It is counterintuitive, but actually makes perfect sense:

def add(item, s=[]):
    s.append(item)
    print len(s)

add(1)     # 1
add(1)     # 2
add(1, []) # 1
add(1, []) # 1
add(1)     # 3

This will print 1 2 1 1 3.

Because it works the same way as

default_s=[]
def add(item, s=default_s):
    s.append(item)

Obviously, if you modify default_s, it retains these modifications.

There are various workarounds, including

def add(item, s=None):
    if not s: s = []
    s.append(item)

or you could do this:

def add(self, item, s=None):
    if not s: s = self.makeDefaultS()
    s.append(item)

Then the method makeDefaultS will have access to self.

Another variation:

import types
def add(item, s=lambda self:[]):
    if isinstance(s, types.FunctionType): s = s("example")
    s.append(item)

here the default value of s is a factory function.

You can combine all these techniques:

class Foo:
    import types
    def add(self, item, s=Foo.defaultFactory):
        if isinstance(s, types.FunctionType): s = s(self)
        s.append(item)

    def defaultFactory(self):
        """ Can be overridden in a subclass, too!"""
        return []

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

Make: how to continue after a command fails?

Return successfully by blocking rm's returncode behind a pipe with the true command, which always returns 0 (success)

rm file | true

How can I add 1 day to current date?

If you want add a day (24 hours) to current datetime you can add milliseconds like this:

new Date(Date.now() + ( 3600 * 1000 * 24))

Is HTML considered a programming language?

I get around this problem by not having a "programming languages" section on my resume. Instead I label it simply as "languages", and I stick HTML and CSS at the end. I'd rather make life easier for the reviewer so that they can see whether mine checks-off all their requirements.

Only fools would disregard an applicant because he or she listed HTML under "languages" instead of some other label, especially since there is no industry standard. And who wants to work for fools?

How to set cache: false in jQuery.get call

I'm very late in the game, but this might help others. I hit this same problem with $.get and I didn't want to blindly turn off caching and I didn't like the timestamp patch. So after a little research I found that you can simply use $.post instead of $.get which does NOT use caching. Simple as that. :)

http://localhost/ not working on Windows 7. What's the problem?

Before installing Wamp, go to controlpanel=> Adminstrative tools => IIS Manager and turn off the IIS server. Install wamp and everything works fine. When IIS is on it also uses port 80. You can go through a lot of changing the ports and permissions for wamp but I have found this the quickest and easiest method of getting wamp to run successfully.

How do I get next month date from today's date and insert it in my database?

If you want a specific date in next month, you can do this:

// Calculate the timestamp
$expire = strtotime('first day of +1 month');

// Format the timestamp as a string
echo date('m/d/Y', $expire);

Note that this actually works more reliably where +1 month can be confusing. For example...

Current Day   | first day of +1 month     | +1 month
---------------------------------------------------------------------------
2015-01-01    | 2015-02-01                | 2015-02-01
2015-01-30    | 2015-02-01                | 2015-03-02  (skips Feb)
2015-01-31    | 2015-02-01                | 2015-03-03  (skips Feb)
2015-03-31    | 2015-04-01                | 2015-05-01  (skips April)
2015-12-31    | 2016-01-01                | 2016-01-31

How to hide/show more text within a certain length (like youtube)

So much answers and all them good, but I will suggest my own, maybe it will be usefull for somebody.

We have HTML in the template:

<div class="listing-item-excerpt" id="listing-item-excerpt-<?= $task['id'] ?>">
    <?= mb_substr($txt, 0, 150) ?><span class="complete_txt"><?= mb_substr($txt, 150) ?></span>
    <a href="javascript: show_more_less(<?= $task['id'] ?>);void(0);" class="more_less_btn" data-more-txt="<?= __('... show more') ?>" data-less-txt="&nbsp;<?= __('show less') ?>" data-state="0"><?= __('... show more') ?></a>
</div>

JS function for toggling which:

function show_more_less(task_id) {

    var btn = jQuery('#listing-item-excerpt-' + task_id).find('.more_less_btn');
    var txt_container = jQuery('#listing-item-excerpt-' + task_id).find('.complete_txt');
    var state = parseInt(jQuery(btn).data('state'), 10);
    if (state === 0) {
        jQuery(txt_container).show();
        jQuery(btn).text(jQuery(btn).data('less-txt'));
        jQuery(btn).data('state', 1);
    } else {
        jQuery(txt_container).hide();
        jQuery(btn).text(jQuery(btn).data('more-txt'));
        jQuery(btn).data('state', 0);
    }
}

How to get the bluetooth devices as a list?

package com.sekurtrack.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    private BluetoothAdapter BA;
    private ArrayList<String> mDeviceList = new ArrayList<String>();
    private Set<BluetoothDevice> pairedDevices;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.devicesList);



        BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

       /* BA = BluetoothAdapter.getDefaultAdapter();
        pairedDevices = BA.getBondedDevices();
        ArrayList list = new ArrayList();
        for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
        final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);*/

    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device.getName() + "\n" + device.getAddress());
                Log.i("BT1", device.getName() + "\n" + device.getAddress());
                listView.setAdapter(new ArrayAdapter<String>(context,
                        android.R.layout.simple_list_item_1, mDeviceList));
            }
        }
    };
}

Error: Module not specified (IntelliJ IDEA)

Faced the same issue. To solve it,

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

If you're looking for a minimal solution that invalidates the cache, this edited version of Dr Manhattan's solution should be sufficient. Note that I'm specifying the root / directory to indicate I want the whole site refreshed.

export AWS_ACCESS_KEY_ID=<Key>
export AWS_SECRET_ACCESS_KEY=<Secret>
export AWS_DEFAULT_REGION=eu-west-1

echo "Invalidating cloudfrond distribution to get fresh cache"
aws cloudfront create-invalidation --distribution-id=<distributionId> --paths / --profile=<awsprofile>

Region Codes can be found here

You'll also need to create a profile using the aws cli. Use the aws configure --profile option. Below is an example snippet from Amazon.

$ aws configure --profile user2
AWS Access Key ID [None]: AKIAI44QH8DHBEXAMPLE
AWS Secret Access Key [None]: je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
Default region name [None]: us-east-1
Default output format [None]: text

MySQL - UPDATE multiple rows with different values in one query

You can use a CASE statement to handle multiple if/then scenarios:

UPDATE table_to_update 
SET  cod_user= CASE WHEN user_rol = 'student' THEN '622057'
                   WHEN user_rol = 'assistant' THEN '2913659'
                   WHEN user_rol = 'admin' THEN '6160230'
               END
    ,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
  AND cod_office = '17389551';

Set selected radio from radio group with a value

Pure JavaScript version:

document.querySelector('input[name="myradio"][value="5"]').checked = true;

Get Max value from List<myType>

Easiest way is to use System.Linq as previously described

using System.Linq;

public int GetHighestValue(List<MyTypes> list)
{
    return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}

This is also possible with a Dictionary

using System.Linq;

public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
    return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}

Error while installing json gem 'mkmf.rb can't find header files for ruby'

In Fedora 21 and up, you simply open a terminal and install the Ruby Development files as root.

dnf install ruby-devel

How to load a UIView using a nib file created with Interface Builder

I would use UINib to instantiate a custom UIView to be reused

UINib *customNib = [UINib nibWithNibName:@"MyCustomView" bundle:nil];
MyCustomViewClass *customView = [[customNib instantiateWithOwner:self options:nil] objectAtIndex:0];
[self.view addSubview:customView];

Files needed in this case are MyCustomView.xib, MyCustomViewClass.h and MyCustomViewClass.m Note that [UINib instantiateWithOwner] returns an array, so you should use the element which reflects the UIView you want to re-use. In this case it's the first element.

How to call any method asynchronously in c#

public partial class MainForm : Form
{
    Image img;
    private void button1_Click(object sender, EventArgs e)
    {
        LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
    }

    private void LoadImageAsynchronously(string url)
    {
        /*
        This is a classic example of how make a synchronous code snippet work asynchronously.
        A class implements a method synchronously like the WebClient's DownloadData(…) function for example
            (1) First wrap the method call in an Anonymous delegate.
            (2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
            (3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
            (4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
        */
        try
        {
            Func<Image> load_image_Async = delegate()
            {
                WebClient wc = new WebClient();
                Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
                wc.Dispose();
                return bmpLocal;
            };

            Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
            {
                Func<Image> ss = (Func<Image>)ar.AsyncState;
                Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);

                if (img != null) img.Dispose();
                if (myBmp != null)
                    img = myBmp;
                Invalidate();
                //timer.Enabled = true;
            };
            //load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);             
            load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);             
        }
        catch (Exception ex)
        {

        }
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        if (img != null)
        {
            Graphics grfx = e.Graphics;
            grfx.DrawImage(img,new Point(0,0));
        }
    }

Toggle Class in React

Ori Drori's comment is correct, you aren't doing this the "React Way". In React, you should ideally not be changing classes and event handlers using the DOM. Do it in the render() method of your React components; in this case that would be the sideNav and your Header. A rough example of how this would be done in your code is as follows.

HEADER

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

render() {
    return (
        <div className="header">
            <i className="border hide-on-small-and-down"></i>
            <div className="container">
                <a ref="btn" href="#" className="btn-menu show-on-small"
                onClick=this.showNav><i></i></a>
                <Menu className="menu hide-on-small-and-down"/>
                <Sidenav ref="sideNav"/>
            </div>
        </div>
    )
}

showNav() {
  this.refs.sideNav.show();
}
}

SIDENAV

 class SideNav extends React.Component {
   constructor(props) {
     super(props);
     this.state = {
       open: false
     }
   }

   render() {
     if (this.state.open) {
       return ( 
         <div className = "sideNav">
            This is a sidenav 
         </div>
       )
     } else {
       return null;
     }

   }

   show() {
     this.setState({
       open: true
     })
   }
 }

You can see here that we are not toggling classes but using the state of the components to render the SideNav. This way, or similar is the whole premise of using react. If you are using bootstrap, there is a library which integrates bootstrap elements with the react way of doing things, allowing you to use the same elements but set state on them instead of directly manipulating the DOM. It can be found here - https://react-bootstrap.github.io/

Hope this helps, and enjoy using React!

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I had many projects of different type in my solution and I could not run the Xunit test project. I unloaded all of them except my Xunit project and then rebuild the solution the tests appeared in visual studio and I could run them.

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

How to open VMDK File of the Google-Chrome-OS bundle 2012?

Generally, this is how you open an OS folder containing a bunch of vdmk files on VMware Player.

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

Padding or margin value in pixels as integer using jQuery

Here's how you can get the surrounding dimentions:

var elem = $('#myId');

var marginTopBottom  = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight  = elem.outerWidth(true)  - elem.outerWidth();

var borderTopBottom  = elem.outerHeight() - elem.innerHeight();
var borderLeftRight  = elem.outerWidth()  - elem.innerWidth();

var paddingTopBottom  = elem.innerHeight() - elem.height();
var paddingLeftRight  = elem.innerWidth()  - elem.width();

Pay attention that each variable, paddingTopBottom for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)

How to iterate for loop in reverse order in swift?

You can consider using the C-Style while loop instead. This works just fine in Swift 3:

var i = 5 
while i > 0 { 
    print(i)
    i -= 1
}

Why is width: 100% not working on div {display: table-cell}?

How about this? (jsFiddle link)

CSS

ul {
    background: #CCC;
    height: 1000%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
    position: absolute;
}
li {
 background-color: #EBEBEB;
    border-bottom: 1px solid #CCCCCC;
    border-right: 1px solid #CCCCCC;
    display: table;
    height: 180px;
    overflow: hidden;
    width: 200px;
}
.divone{
    display: table-cell;
    margin: 0 auto;
    text-align: center;
    vertical-align: middle;
    width: 100%; 

}
img {
    width: 100%;
    height: 410px;
}
.wrapper {
  position: absolute;
}

Toggle input disabled attribute using jQuery

I guess to get full browser comparability disabled should set by the value disabled or get removed!
Here is a small plugin that I've just made:

(function($) {
    $.fn.toggleDisabled = function() {
        return this.each(function() {
            var $this = $(this);
            if ($this.attr('disabled')) $this.removeAttr('disabled');
            else $this.attr('disabled', 'disabled');
        });
    };
})(jQuery);

Example link.

EDIT: updated the example link/code to maintaining chainability!
EDIT 2:
Based on @lonesomeday comment, here's an enhanced version:

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

not:first-child selector

not(:first-child) does not seem to work anymore. At least with the more recent versions of Chrome and Firefox.

Instead, try this:

ul:not(:first-of-type) {}

Align printf output in Java

Format specifications for printf and printf-like methods take an optional width parameter.

System.out.printf( "%10d. %25s $%25.2f\n",
                   i + 1, BOOK_TYPE[i], COST[i] );

Adjust widths to desired values.

Should I test private methods or only public ones?

If I find that the private method is huge or complex or important enough to require its own tests, I just put it in another class and make it public there (Method Object). Then I can easily test the previously private but now public method that now lives on its own class.

How to make full screen background in a web page

um why not just set an image to the bottom layer and forgo all the annoyances

<img src='yourmom.png' style='position:fixed;top:0px;left:0px;width:100%;height:100%;z-index:-1;'>

Warning about `$HTTP_RAW_POST_DATA` being deprecated

Been awhile until I came across this error. Put up my answer for anyone who may stumble upon this issue.

The error only means that you are sending an empty POST request. This error is commonly found on HTTPRequests with no parameters passed. To avoid this error, you can always add a parameter to the POST without changing the php.ini.

Like:

$.post(URL_HERE
    ,{addedvar : 'anycontent'}
    ,function(d){
       doAnyHere(d);
    }
    ,'json' //or 'html','text'
);

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

Sort list in C# with LINQ

Well, the simplest way using LINQ would be something like this:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true, but the first form makes it clearer IMO, because everyone knows that 0 < 1.

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. If you want to sort in place, you should use the List<T>.Sort method.

How to make a phone call programmatically?

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
   final Button button = (Button) findViewById(R.id.btn_call);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String mobileNo = "123456789";
            String uri = "tel:" + mobileNo.trim();
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse(uri));
            startActivity(intent);
        }
    });*
 }

Package signatures do not match the previously installed version

This happens when you have installed app with diffrent versions on your mobile/emulator phone.

Simply uninstall existing app will solve the problem

How can I check what version/edition of Visual Studio is installed programmatically?

All the information in this thread is now out of date with the recent release of vswhere. Download that and use it.

Create numpy matrix filled with NaNs

Another option is to use numpy.full, an option available in NumPy 1.8+

a = np.full([height, width, 9], np.nan)

This is pretty flexible and you can fill it with any other number that you want.

How do I align spans or divs horizontally?

    <!-- CSS -->
<style rel="stylesheet" type="text/css">
.all { display: table; }
.menu { float: left; width: 30%; }
.content { margin-left: 35%; }
</style>

<!-- HTML -->
<div class="all">
<div class="menu">Menu</div>
<div class="content">Content</div>
</div>

another... try to use float: left; or right;, change the width for other values... it shoul work... also note that the 10% that arent used by the div its betwen them... sorry for bad english :)

Uint8Array to string in Javascript

The solution given by Albert works well as long as the provided function is invoked infrequently and is only used for arrays of modest size, otherwise it is egregiously inefficient. Here is an enhanced vanilla JavaScript solution that works for both Node and browsers and has the following advantages:

• Works efficiently for all octet array sizes

• Generates no intermediate throw-away strings

• Supports 4-byte characters on modern JS engines (otherwise "?" is substituted)

var utf8ArrayToStr = (function () {
    var charCache = new Array(128);  // Preallocate the cache for the common single byte chars
    var charFromCodePt = String.fromCodePoint || String.fromCharCode;
    var result = [];

    return function (array) {
        var codePt, byte1;
        var buffLen = array.length;

        result.length = 0;

        for (var i = 0; i < buffLen;) {
            byte1 = array[i++];

            if (byte1 <= 0x7F) {
                codePt = byte1;
            } else if (byte1 <= 0xDF) {
                codePt = ((byte1 & 0x1F) << 6) | (array[i++] & 0x3F);
            } else if (byte1 <= 0xEF) {
                codePt = ((byte1 & 0x0F) << 12) | ((array[i++] & 0x3F) << 6) | (array[i++] & 0x3F);
            } else if (String.fromCodePoint) {
                codePt = ((byte1 & 0x07) << 18) | ((array[i++] & 0x3F) << 12) | ((array[i++] & 0x3F) << 6) | (array[i++] & 0x3F);
            } else {
                codePt = 63;    // Cannot convert four byte code points, so use "?" instead
                i += 3;
            }

            result.push(charCache[codePt] || (charCache[codePt] = charFromCodePt(codePt)));
        }

        return result.join('');
    };
})();

Java: recommended solution for deep cloning/copying an instance

Since version 2.07 Kryo supports shallow/deep cloning:

Kryo kryo = new Kryo();
SomeClass someObject = ...
SomeClass copy1 = kryo.copy(someObject);
SomeClass copy2 = kryo.copyShallow(someObject);

Kryo is fast, at the and of their page you may find a list of companies which use it in production.

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

Firefox simply does not show custom onbeforeunload messages. Mozilla say they are protecing end users from malicious sites that might show misleading text.

Angular 2 : No NgModule metadata found

The problem is in your main.ts file.

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

You are trying to bootstrap App, which is not a real module. Delete these two lines and replace with the following line:

platformBrowserDynamic().bootstrapModule(AppModule);

and it will fix your error.

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

There is an official github gem which, I think, does this. I'll try to add more information as I learn, but I'm only just now discovering this gem, so I don't know much yet.

UPDATE: After setting my API key, I am able to create a new repo on github via the create command, however I am not able to use the create-from-local command, which is supposed to take the current local repo and make a corresponding remote out on github.

$ gh create-from-local
=> error creating repository

If anyone has some insight on this, I'd love to know what I'm doing wrong. There's already an issue filed.

UPDATE: I did eventually get this to work. I'm not exactly sure how to re-produce the issue, but I just started from scratch (deleted the .git folder)

git init
git add .emacs
git commit -a -m "adding emacs"

Now this line will create the remote repo and even push to it, but unfortunately I don't think I can specify the name of the repo I'd like. I wanted it to be called "dotfiles" out on github, but the gh gem just used the name of the current folder, which was "jason" since I was in my home folder. (I added a ticket asking for the desired behavior)

gh create-from-local

This command, on the other hand, does accept an argument to specify the name of the remote repo, but it's intended for starting a new project from scratch, i.e. after you call this command, you get a new remote repo that's tracking a local repo in a newly-created subfolder relative to your current position, both with the name specified as the argument.

gh create dotfiles

Java: Convert a String (representing an IP) to InetAddress

Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

InetAddress javadoc

How to check for an empty struct?

Keep in mind that with pointers to struct you'd have to dereference the variable and not compare it with a pointer to empty struct:

session := &Session{}
if (Session{}) == *session {
    fmt.Println("session is empty")
}

Check this playground.

Also here you can see that a struct holding a property which is a slice of pointers cannot be compared the same way...

What's the CMake syntax to set and use variables?

$ENV{FOO} for usage, where FOO is being picked up from the environment variable. otherwise use as ${FOO}, where FOO is some other variable. For setting, SET(FOO "foo") would be used in CMake.

How to get Enum Value from index in Java?

Try this

Months.values()[index]

Can't include C++ headers like vector in Android NDK

If you are using Android studio and you are still seeing the message "error: vector: No such file or directory" (or other stl related errors) when you're compiling using ndk, then this might help you.

In your project, open the module's build.gradle file (not your project's build.grade, but the one that is for your module) and add 'stl "stlport_shared"' within the ndk element in defaultConfig.

For eg:

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.domain.app"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"

        ndk {
            moduleName "myModuleName"
            stl "stlport_shared"
        }
    }
}

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

How to convert any date format to yyyy-MM-dd

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

How to add hyperlink in JLabel?

Maybe use JXHyperlink from SwingX instead. It extends JButton. Some useful links:

SQL: How to perform string does not equal

Another way of getting the results

SELECT * from table WHERE SUBSTRING(tester, 1, 8)  <> 'username' or tester is null

How to convert float value to integer in php?

There is always intval() - Not sure if this is what you were looking for...

example: -

$floatValue = 4.5;
echo intval($floatValue);    // Returns 4

It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.

Here is some documentation for this: - http://php.net/manual/en/function.intval.php

Empty ArrayList equals null

No, because it contains items there must be an instance of it. Its items being null is irrelevant, so the statment ((arrayList) != null) == true

how to implement regions/code collapse in javascript

Blog entry here explains it and this MSDN question.

You have to use Visual Studio 2003/2005/2008 Macros.

Copy + Paste from Blog entry for fidelity sake:

  1. Open Macro Explorer
  2. Create a New Macro
  3. Name it OutlineRegions
  4. Click Edit macro and paste the following VB code:
Option Strict Off
Option Explicit Off

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Collections

Public Module JsMacros

    Sub OutlineRegions()
        Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection

        Const REGION_START As String = "//#region"
        Const REGION_END As String = "//#endregion"

        selection.SelectAll()
        Dim text As String = selection.Text
        selection.StartOfDocument(True)

        Dim startIndex As Integer
        Dim endIndex As Integer
        Dim lastIndex As Integer = 0
        Dim startRegions As Stack = New Stack()

        Do
            startIndex = text.IndexOf(REGION_START, lastIndex)
            endIndex = text.IndexOf(REGION_END, lastIndex)

            If startIndex = -1 AndAlso endIndex = -1 Then
                Exit Do
            End If

            If startIndex <> -1 AndAlso startIndex < endIndex Then
                startRegions.Push(startIndex)
                lastIndex = startIndex + 1
            Else
                ' Outline region ...
                selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
                selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
                selection.OutlineSection()

                lastIndex = endIndex + 1
            End If
        Loop

        selection.StartOfDocument()
    End Sub

    Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
        Dim lineNumber As Integer = 1
        Dim i As Integer = 0

        While i < index
            If text.Chars(i) = vbCr Then
                lineNumber += 1
                i += 1
            End If

            i += 1
        End While

        Return lineNumber
    End Function

End Module
  1. Save the Macro and Close the Editor
  2. Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox
  3. now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+E. I don't know why - I just entered it first time and use it now :)

How to convert integer to decimal in SQL Server query?

select cast (height as decimal)/10 as HeightDecimal

Application Installation Failed in Android Studio

Here's my solution (there's no need to deactivate instant run) Do all these steps in the stated order:

1- Gradle Build (root level)

gradle

2 - Gradle build + clean (app level)

gradle app

3 - Choose app on the top bar (left of Run 'app')

4 - Clean Project:

Navigate to Build > Clean Project

And it should work now! You shouldn't disable instant run if you follow these steps

How to remove duplicates from Python list and keep order?

If your input is already sorted, then there may be a simpler way to do it:

from operator import itemgetter
from itertools import groupby
unique_list = list(map(itemgetter(0), groupby(yourList)))

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

I was seeing this issue with an older version of Lombok when compiling under JDK8. Setting the project back to JDK7 made the issue go away.

Storing integer values as constants in Enum manner in java

I found this to be helpful:

http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/

public enum Difficulty
{
    EASY(0),
    MEDIUM(1),
    HARD(2);

    /**
    * Value for this difficulty
    */
    public final int Value;

    private Difficulty(int value)
    {
        Value = value;
    }

    // Mapping difficulty to difficulty id
    private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
    static
    {
        for (Difficulty difficulty : Difficulty.values())
            _map.put(difficulty.Value, difficulty);
    }

    /**
    * Get difficulty from value
    * @param value Value
    * @return Difficulty
    */
    public static Difficulty from(int value)
    {
        return _map.get(value);
    }
}

Android, How can I Convert String to Date?

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

View array in Visual Studio debugger?

If you have a large array and only want to see a subsection of the array you can type this into the watch window;

ptr+100,10

to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.

how to kill the tty in unix

you do not need to know pts number, just type:

ps all | grep bash

then:

kill pid1 pid2 pid3 ...

Apache default VirtualHost

The NameVirtualHost option would be a good option.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

Why am I getting Unknown error in line 1 of pom.xml?

You just need a latest Eclipse or Spring tool suite 4.5 and above.Nothing else.refresh project and it works

How to remove border from specific PrimeFaces p:panelGrid?

for me only the following code works

.noBorder tr {
border-width: 0 ;
}
.ui-panelgrid td{
    border-width: 0
}

<p:panelGrid id="userFormFields" columns="2" styleClass="noBorder" >
</p:panelGrid>

Set value for particular cell in pandas DataFrame using index

I would suggest:

df.loc[index_position, "column_name"] = some_value

How do I change the font-size of an <option> element within <select>?

Like most form controls in HTML, the results of applying CSS to <select> and <option> elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option> element directly --- if you do Inspect Element on it, you'll see the font-size: 14px declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.

However, Chrome will let you apply font styles to the <optgroup> element, so to achieve the result you want you can wrap all the <option>s in an <optgroup> and then apply your font styles to a .styled-select optgroup selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.

Forked to a new JSFiddle to show you what I mean:

http://jsfiddle.net/zRtbZ/

Replace preg_replace() e modifier with preg_replace_callback

In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

So a /e argument of

'do_stuff(\\1) . "and" . do_stuff(\\2)'

could become a callback of

function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }

Or in your case

'strtoupper("\\2")'

could become

function($m) { return strtoupper($m[2]); }

Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

function stuffy_callback($things) {
    return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');

As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

'do_stuff(\\1, $foo)'

then the new callback might look like

function($m) use ($foo) { return do_stuff($m[1], $foo); }

Gotchas

  • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
  • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.

asp.net Button OnClick event not firing

Even i had two forms one for desktop view and other for mobile view , Removed one formed worked for me . I dint knew asp.page should have only one form.

updating table rows in postgres using subquery

@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.

WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;

Hope this helps... :D

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

You can use Oracle.ManagedDataAccess.dll instead (download from Oracle), include that dll in you project bin dir, add reference to that dll in the project. In code, "using Oracle.MangedDataAccess.Client". Deploy project to server as usual. No need install Oracle Client on server. No need to add assembly info in web.config.

Display SQL query results in php

You need to do a while loop to get the result from the SQL query, like this:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

Shell Script — Get all files modified after <date>

You can get a list of files last modified later than x days ago with:

find . -mtime -x

Then you just have to tar and zip files in the resulting list, e.g.:

tar czvf mytarfile.tgz `find . -mtime -30`

for all files modified during last month.

How do I resolve this "ORA-01109: database not open" error?

If you are using 19c then just follow the following steps

  1. Login with sys user.
  2. alter the session to the pluggable database with the following command.
  3. SQL>alter session set container=orclpdb;
  4. Next startup the database.
  5. SQL>startup After that database will not show the above error.

Best HTML5 markup for sidebar

Based on this HTML5 Doctor diagram, I'm thinking this may be the best markup:

<aside class="sidebar">
    <article id="widget_1" class="widget">...</article>
    <article id="widget_2" class="widget">...</article>
    <article id="widget_3" class="widget">...</article>
</aside> <!-- end .sidebar -->

I think it's clear that <aside> is the appropriate element as long as it's outside the main <article> element.

Now, I'm thinking that <article> is also appropriate for each widget in the aside. In the words of the W3C:

The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

How to count how many values per level in a given factor?

Use the package plyr with lapply to get frequencies for every value (level) and every variable (factor) in your data frame.

library(plyr)
lapply(df, count)

How to clone ArrayList and also clone its contents?

I have found a way, you can use json to serialize/unserialize the list. The serialized list holds no reference to the original object when unserialized.

Using gson:

List<CategoryModel> originalList = new ArrayList<>(); // add some items later
String listAsJson = gson.toJson(originalList);
List<CategoryModel> newList = new Gson().fromJson(listAsJson, new TypeToken<List<CategoryModel>>() {}.getType());

You can do that using jackson and any other json library too.

How can I get customer details from an order in WooCommerce?

2017-2020 WooCommerce versions 3+ and CRUD Objects

1). You can use getter methods from WC_Order and WC_Abstract_Order classes on the WC_Order object instance like:

// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );

// Get the Customer ID (User ID)
$customer_id = $order->get_customer_id(); // Or $order->get_user_id();

// Get the WP_User Object instance
$user = $order->get_user();

// Get the WP_User roles and capabilities
$user_roles = $user->roles;

// Get the Customer billing email
$billing_email  = $order->get_billing_email();

// Get the Customer billing phone
$billing_phone  = $order->get_billing_phone();

// Customer billing information details
$billing_first_name = $order->get_billing_first_name();
$billing_last_name  = $order->get_billing_last_name();
$billing_company    = $order->get_billing_company();
$billing_address_1  = $order->get_billing_address_1();
$billing_address_2  = $order->get_billing_address_2();
$billing_city       = $order->get_billing_city();
$billing_state      = $order->get_billing_state();
$billing_postcode   = $order->get_billing_postcode();
$billing_country    = $order->get_billing_country();

// Customer shipping information details
$shipping_first_name = $order->get_shipping_first_name();
$shipping_last_name  = $order->get_shipping_last_name();
$shipping_company    = $order->get_shipping_company();
$shipping_address_1  = $order->get_shipping_address_1();
$shipping_address_2  = $order->get_shipping_address_2();
$shipping_city       = $order->get_shipping_city();
$shipping_state      = $order->get_shipping_state();
$shipping_postcode   = $order->get_shipping_postcode();
$shipping_country    = $order->get_shipping_country();

2). You can also use the WC_Order get_data() method, to get an unprotected data array from Order meta data like:

// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );

// Get the Order meta data in an unprotected array
$data  = $order->get_data(); // The Order data

$order_id        = $data['id'];
$order_parent_id = $data['parent_id'];

// Get the Customer ID (User ID)
$customer_id     = $data['customer_id'];

## BILLING INFORMATION:

$billing_email      = $data['billing']['email'];
$billing_phone      = $order_data['billing']['phone'];

$billing_first_name = $data['billing']['first_name'];
$billing_last_name  = $data['billing']['last_name'];
$billing_company    = $data['billing']['company'];
$billing_address_1  = $data['billing']['address_1'];
$billing_address_2  = $data['billing']['address_2'];
$billing_city       = $data['billing']['city'];
$billing_state      = $data['billing']['state'];
$billing_postcode   = $data['billing']['postcode'];
$billing_country    = $data['billing']['country'];

## SHIPPING INFORMATION:

$shipping_first_name = $data['shipping']['first_name'];
$shipping_last_name  = $data['shipping']['last_name'];
$shipping_company    = $data['shipping']['company'];
$shipping_address_1  = $data['shipping']['address_1'];
$shipping_address_2  = $data['shipping']['address_2'];
$shipping_city       = $data['shipping']['city'];
$shipping_state      = $data['shipping']['state'];
$shipping_postcode   = $data['shipping']['postcode'];
$shipping_country    = $data['shipping']['country'];

Now to get the user account data (from an Order ID):

1). You can use the methods from WC_Customer Class:

// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );

// Get an instance of the WC_Customer Object from the user ID
$customer = new WC_Customer( $user_id );

$username     = $customer->get_username(); // Get username
$user_email   = $customer->get_email(); // Get account email
$first_name   = $customer->get_first_name();
$last_name    = $customer->get_last_name();
$display_name = $customer->get_display_name();

// Customer billing information details (from account)
$billing_first_name = $customer->get_billing_first_name();
$billing_last_name  = $customer->get_billing_last_name();
$billing_company    = $customer->get_billing_company();
$billing_address_1  = $customer->get_billing_address_1();
$billing_address_2  = $customer->get_billing_address_2();
$billing_city       = $customer->get_billing_city();
$billing_state      = $customer->get_billing_state();
$billing_postcode   = $customer->get_billing_postcode();
$billing_country    = $customer->get_billing_country();

// Customer shipping information details (from account)
$shipping_first_name = $customer->get_shipping_first_name();
$shipping_last_name  = $customer->get_shipping_last_name();
$shipping_company    = $customer->get_shipping_company();
$shipping_address_1  = $customer->get_shipping_address_1();
$shipping_address_2  = $customer->get_shipping_address_2();
$shipping_city       = $customer->get_shipping_city();
$shipping_state      = $customer->get_shipping_state();
$shipping_postcode   = $customer->get_shipping_postcode();
$shipping_country    = $customer->get_shipping_country();

2). The WP_User object (WordPress):

// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );

// Get the WP_User instance Object
$user = new WP_User( $user_id );

$username     = $user->username; // Get username
$user_email   = $user->email; // Get account email
$first_name   = $user->first_name;
$last_name    = $user->last_name;
$display_name = $user->display_name;

// Customer billing information details (from account)
$billing_first_name = $user->billing_first_name;
$billing_last_name  = $user->billing_last_name;
$billing_company    = $user->billing_company;
$billing_address_1  = $user->billing_address_1;
$billing_address_2  = $user->billing_address_2;
$billing_city       = $user->billing_city;
$billing_state      = $user->billing_state;
$billing_postcode   = $user->billing_postcode;
$billing_country    = $user->billing_country;

// Customer shipping information details (from account)
$shipping_first_name = $user->shipping_first_name;
$shipping_last_name  = $user->shipping_last_name;
$shipping_company    = $user->shipping_company;
$shipping_address_1  = $user->shipping_address_1;
$shipping_address_2  = $user->shipping_address_2;
$shipping_city       = $user->shipping_city;
$shipping_state      = $user->shipping_state;
$shipping_postcode   = $user->shipping_postcode;
$shipping_country    = $user->shipping_country;

Related: How to get WooCommerce order details

How can I save an image with PIL?

You should be able to simply let PIL get the filetype from extension, i.e. use:

j.save("C:/Users/User/Desktop/mesh_trans.bmp")

Converting string to numeric

I suspect you are having a problem with factors. For example,

> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8

Some comments:

  • You mention that your vector contains the characters "Down" and "NoData". What do expect/want as.numeric to do with these values?
  • In read.csv, try using the argument stringsAsFactors=FALSE
  • Are you sure it's sep="/t and not sep="\t"
  • Use the command head(pitchman) to check the first fews rows of your data
  • Also, it's very tricky to guess what your problem is when you don't provide data. A minimal working example is always preferable. For example, I can't run the command pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t") since I don't have access to the data set.

split python source code into multiple files?

You can do the same in python by simply importing the second file, code at the top level will run when imported. I'd suggest this is messy at best, and not a good programming practice. You would be better off organizing your code into modules

Example:

F1.py:

print "Hello, "
import f2

F2.py:

print "World!"

When run:

python ./f1.py
Hello, 
World!

Edit to clarify: The part I was suggesting was "messy" is using the import statement only for the side effect of generating output, not the creation of separate source files.

Java client certificates over HTTPS/SSL

I use the Apache commons HTTP Client package to do this in my current project and it works fine with SSL and a self-signed cert (after installing it into cacerts like you mentioned). Please take a look at it here:

http://hc.apache.org/httpclient-3.x/tutorial.html

http://hc.apache.org/httpclient-3.x/sslguide.html

How to open an existing project in Eclipse?

from Eclipse main gui: select "Window->Show View->Other->General->Project Explorer" Double-clicking on "Project Explorer" brings up the "Project Explorer" window which shows every project in your workspace. That worked for me.

Good luck.

Adding input elements dynamically to form

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var max_fields = 10;_x000D_
    var wrapper = $(".container1");_x000D_
    var add_button = $(".add_form_field");_x000D_
_x000D_
    var x = 1;_x000D_
    $(add_button).click(function(e) {_x000D_
        e.preventDefault();_x000D_
        if (x < max_fields) {_x000D_
            x++;_x000D_
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
        } else {_x000D_
            alert('You Reached the limits')_x000D_
        }_x000D_
    });_x000D_
_x000D_
    $(wrapper).on("click", ".delete", function(e) {_x000D_
        e.preventDefault();_x000D_
        $(this).parent('div').remove();_x000D_
        x--;_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
    <button class="add_form_field">Add New Field &nbsp; _x000D_
      <span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
    </button>_x000D_
    <div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Refer Demo Here

Python method for reading keypress?

See the MSDN getch docs. Specifically:

The _getch and_getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

The Python function returns a character. you can use ord() to get an integer value you can test, for example keycode = ord(msvcrt.getch()).

So if you read an 0x00 or 0xE0, read it a second time to get the key code for an arrow or function key. From experimentation, 0x00 precedes F1-F10 (0x3B-0x44) and 0xE0 precedes arrow keys and Ins/Del/Home/End/PageUp/PageDown.

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I have also got stuck into this and believe me disabling SELinux is not a good idea.

Please just use below and you are good,

sudo restorecon -R /var/www/mysite

Enjoy..

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

I have come to point out the answer nobody seems to see here. You can fullfill all requests you have made with pure CSS and it's very simple. Just use Media Queries. Media queries can check the orientation of the user's screen, or viewport. Then you can style your images depending on the orientation.

Just set your default CSS on your images like so:

img {
   width:auto;
   height:auto;
   max-width:100%;
   max-height:100%;
}

Then use some media queries to check your orientation and that's it!

@media (orientation: landscape) { img { height:100%; } }
@media (orientation: portrait) { img { width:100%; } }

You will always get an image that scales to fit the screen, never loses aspect ratio, never scales larger than the screen, never clips or overflows.

To learn more about these media queries, you can read MDN's specs.

Centering

To center your image horizontally and vertically, just use the flex box model. Use a parent div set to 100% width and height, like so:

div.parent {
   display:flex;
   position:fixed;
   left:0px;
   top:0px;
   width:100%;
   height:100%;
   justify-content:center;
   align-items:center;
}

With the parent div's display set to flex, the element is now ready to use the flex box model. The justify-content property sets the horizontal alignment of the flex items. The align-items property sets the vertical alignment of the flex items.

Conclusion

I too had wanted these exact requirements and had scoured the web for a pure CSS solution. Since none of the answers here fulfilled all of your requirements, either with workarounds or settling upon sacrificing a requirement or two, this solution really is the most straightforward for your goals; as it fulfills all of your requirements with pure CSS.

EDIT: The accepted answer will only appear to work if your images are large. Try using small images and you will see that they can never be larger than their original size.

How to edit the size of the submit button on a form?

Using CSS you can set a style for that specific button using the id (#) selector:

#search {
    width: 20em;  height: 2em;
}

or if you want all submit buttons to be a particular size:

input[type=submit] {
    width: 20em;  height: 2em;
}

or if you want certain classes of button to be a particular style you can use CSS classes:

<input type="submit" id="search" value="Search" class="search" />

and

input.search {
    width: 20em;  height: 2em;
}

I use ems as the measurement unit because they tend to scale better.

How would I get a cron job to run every 30 minutes?

You can use both of ',' OR divide '/' symbols.
But, '/' is better.
Suppose the case of 'every 5 minutes'. If you use ',', you have to write the cron job as following:

0,5,10,15,20,25,30,35,....    *      *     *   * your_command

It means run your_command in every hour in all of defined minutes: 0,5,10,...

However, if you use '/', you can write the following simple and short job:

*/5  *  *  *  *  your_command

It means run your_command in the minutes that are dividable by 5 or in the simpler words, '0,5,10,...'

So, dividable symbol '/' is the best choice always;

tomcat - CATALINA_BASE and CATALINA_HOME variables

If you are running multiple instances of Tomcat on a single host you should set CATALINA_BASE to be equal to the .../tomcat_instance1 or .../tomcat_instance2 directory as appropriate for each instance and the CATALINA_HOME environment variable to the common Tomcat installation whose files will be shared between the two instances.

The CATALINA_BASE environment is optional if you are running a single Tomcat instance on the host and will default to CATALINA_HOME in that case. If you are running multiple instances as you are it should be provided.

There is a pretty good description of this setup in the RUNNING.txt file in the root of the Apache Tomcat distribution under the heading Advanced Configuration - Multiple Tomcat Instances

Iterator over HashMap in Java

Can we see your import block? because it seems that you have imported the wrong Iterator class.

The one you should use is java.util.Iterator

To make sure, try:

java.util.Iterator iter = hm.keySet().iterator();

I personally suggest the following:

Map Declaration using Generics and declaration using the Interface Map<K,V> and instance creation using the desired implementation HashMap<K,V>

Map<Integer, String> hm = new HashMap<>();

and for the loop:

for (Integer key : hm.keySet()) {
    System.out.println("Key = " + key + " - " + hm.get(key));
}

UPDATE 3/5/2015

Found out that iterating over the Entry set will be better performance wise:

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();

}

UPDATE 10/3/2017

For Java8 and streams, your solution will be (Thanks @Shihe Zhang)

 hm.forEach((key, value) -> System.out.println(key + ": " + value))

Can't connect to docker from docker-compose

sudo systemctl start docker - to start the Docker service.

sudo docker-compose up after that.

I have Fedora 26, and trying to solve the same issue I eventually entered Docker Compose on Fedora Developers' page and then Docker on Fedora Developers' page, which helped me.

Probably, docker service considered by community to start with the system and run in background all the time, but for me it was not so obvious, and that's the reason I can think of why there's no popular answer like this one.

On the Fedora Developers' page there's instruction how to enable Docker to start with the system:

sudo systemctl enable docker

Conversion hex string into ascii in bash command line

The echo -e must have been failing for you because of wrong escaping. The following code works fine for me on a similar output from your_program with arguments:

echo -e $(your_program with arguments | sed -e 's/0x\(..\)\.\?/\\x\1/g')

Please note however that your original hexstring consists of non-printable characters.

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

Appending an id to a list if not already present in a string

I agree with other answers that you are doing something weird here. You have a list containing a string with multiple entries that are themselves integers that you are comparing to an integer id.

This is almost surely not what you should be doing. You probably should be taking input and converting it to integers before storing in your list. You could do that with:

input = '350882 348521 350166\r\n'
list.append([int(x) for x in input.split()])

Then your test will pass. If you really are sure you don't want to do what you're currently doing, the following should do what you want, which is to not add the new id that already exists:

list = ['350882 348521 350166\r\n']
id = 348521
if id not in [int(y) for x in list for y in x.split()]:
    list.append(id)
print list

Is it possible to change the speed of HTML's <marquee> tag?

To increase scroll speed of text use attribute

scrollamount
OR
scrolldelay

in the 'marquee' tag. place any integer value which represent how fast you need your text to move

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

How to set background image in Java?

The Path is the only thing you really have to worry about if you are really new to Java. You need to drag your image into the main project file, and it will show up at the very bottom of the list.

Then the file path is pretty straight forward. This code goes into the constructor for the class.

    img = Toolkit.getDefaultToolkit().createImage("/home/ben/workspace/CS2/Background.jpg");

CS2 is the name of my project, and everything before that is leading to the workspace.

Troubleshooting misplaced .git directory (nothing to commit)

I just had this problem myself because I was in the wrong folder. I was nested 1 level in, so there were no git files to be found.

When I execute cd .. to the correct directory, I was able to commit, as expected.

jquery ajax function not working

For the sake of documentation. I spent two days working out an ajax problem and this afternoon when I started testing, my PHP ajax handler wasn't getting called....

Extraordinarily frustrating.

The solution to my problem (which might help others) is the priority of the add_action.

add_action ('wp_ajax_(my handler), array('class_name', 'static_function'), 1);

recalling that the default priority = 10

I was getting a return code of zero and none of my code was being called.

...noting that this wasn't a WordPress problem, I probably misspoke on this question. My apologies.

Convert HH:MM:SS string to seconds only in javascript

Here is maybe a bit more readable form on the original approved answer.

const getSeconds = (hms: string) : number => {
  const [hours, minutes, seconds] = hms.split(':');
  return (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds);
};

Are there dictionaries in php?

Normal array can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.

$names = [
    'bob' => 27,
    'billy' => 43,
    'sam' => 76,
];

$names['bob'];

And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject or you can use SplObjectStorage class which is map (dictionary) implementation allowing objects to be assigned as keys.

Can I configure a subdomain to point to a specific port on my server

If you have access to SRV Records, you can use them to get what you want :)

E.G

A Records

Name: mc1.domain.com
Value: <yourIP>

Name: mc2.domain.com
Value: <yourIP>

SRV Records

Name: _minecraft._tcp.mc1.domain.com
Priority: 5
Weight: 5
Port: 25565
Value: mc1.domain.com

Name: _minecraft._tcp.mc2.domain.com
Priority: 5
Weight: 5
Port: 25566
Value: mc2.domain.com

then in minecraft you can use

mc1.domain.com which will sign you into server 1 using port 25565

and

mc2.domain.com which will sign you into server 2 using port 25566

then on your router you can have it point 25565 and 25566 to the machine with both servers on and Voilà!

Source: This works for me running 2 minecraft servers on the same machine with ports 50500 and 50501

Selenium WebDriver: Wait for complex page with JavaScript to load

Using implicit wait works for me.

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

Refer to this answer Selenium c# Webdriver: Wait Until Element is Present

Min/Max-value validators in asp.net mvc

A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.

public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
    private readonly double _minValue;

    public MinValueAttribute(double minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;  
    }

    public MinValueAttribute(int minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;
    }

    public override bool IsValid(object value)
    {
        return Convert.ToDouble(value) >= _minValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("min", _minValue);
        rule.ValidationParameters.Add("max", Double.MaxValue);
        rule.ValidationType = "range";
        yield return rule;
    }

}

Shortcut to exit scale mode in VirtualBox

If Right Ctrl (Host Key) + C does not work (there have been some issues on Ubuntu), do the following:

1) File > Preferences > Input on the Virtual Machine which is stuck in Scale Mode

2) Change or Reset the Host Key. There's no need to even save after changing the settings

3) Re-open the Virtual Machine and it should be reset!

How to start/stop/restart a thread in Java?

It is impossible to terminate a thread unless the code running in that thread checks for and allows termination.

You said: "Sadly I must kill/restart it ... I don't have complete control over the contents of the thread and for my situation it requires a restart"

If the contents of the thread does not allow for termination of its exectuion then you can not terminate that thread.

In your post you said: "My first attempt was with ExecutorService but I can't seem to find a way for it restart a task. When I use .shutdownnow()..."

If you look at the source of "shutdownnow" it just runs through and interrupts the currently running threads. This will not stop their execution unless the code in those threads checks to see if it has been ineterrupted and, if so, stops execution itself. So shutdownnow is probably not doing what you think.

Let me illustrate what I mean when I say that the contents of the thread must allow for that thread to be terminated:

myExecutor.execute(new Runnable() {
 public void run() {
  while (true) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

That thread will continue to run forever, even though shutdownnow was called, because it never checks to see if it has been terminated or not. This thread, however, will shut down:

myExecutor.execute(new Runnable() {
 public void run() {
  while (!Thread.interrupted()) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

Since this thread checks to see whether or not it has been interrupted / shut down / terminated.

So if you want a thread that you can shut down, you need to make sure it checks to see if it has been interrupted. If you want a thread that you can "shut down" and "restart" you can make a runnable that can take new tasks as was mentioned before.

Why can you not shut down a running thread? Well I actually lied, you can call "yourThread.stop()" but why is this a bad idea? The thread could be in a synchronized (or other critical section, but we will limit ourselves to setions guarded by the syncrhonized key word here) section of code when you stop it. synch blocks are supposed to be executed in their entirity and only by one thread before being accessed by some other thread. If you stop a thread in the middle of a synch block, the protection put into place by the synch block is invalidated and your program will get into an unknown state. Developers make put stuff in synch blocks to keep things in synch, if you use threadInstance.stop() you destroy the meaning of synchronize, what the developer of that code was trying to accomplish and how the developer of that code expected his synchronized blocks to behave.

Use of True, False, and None as return values in Python functions

Use if foo or if not foo. There isn't any need for either == or is for that.

For checking against None, is None and is not None are recommended. This allows you to distinguish it from False (or things that evaluate to False, like "" and []).

Whether get_attr should return None would depend on the context. You might have an attribute where the value is None, and you wouldn't be able to do that. I would interpret None as meaning "unset", and a KeyError would mean the key does not exist in the file.

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

try/catch with InputMismatchException creates infinite loop

To follow debobroto das's answer you can also put after

input.reset();
input.next(); 

I had the same problem and when I tried this. It completely fixed it.

splitting a string into an array in C++ without using vector

#define MAXSPACE 25

string line =  "test one two three.";
string arr[MAXSPACE];
string search = " ";
int spacePos;
int currPos = 0;
int k = 0;
int prevPos = 0;

do
{

    spacePos = line.find(search,currPos);

    if(spacePos >= 0)
    {

        currPos = spacePos;
        arr[k] = line.substr(prevPos, currPos - prevPos);
        currPos++;
        prevPos = currPos;
        k++;
    }


}while( spacePos >= 0);

arr[k] = line.substr(prevPos,line.length());

for(int i = 0; i < k; i++)
{
   cout << arr[i] << endl;
}

Python: Differentiating between row and column vectors

When I tried to compute w^T * x using numpy, it was super confusing for me as well. In fact, I couldn't implement it myself. So, this is one of the few gotchas in NumPy that we need to acquaint ourselves with.

As far as 1D array is concerned, there is no distinction between a row vector and column vector. They are exactly the same.

Look at the following examples, where we get the same result in all cases, which is not true in (the theoretical sense of) linear algebra:

In [37]: w
Out[37]: array([0, 1, 2, 3, 4])

In [38]: x
Out[38]: array([1, 2, 3, 4, 5])

In [39]: np.dot(w, x)
Out[39]: 40

In [40]: np.dot(w.transpose(), x)
Out[40]: 40

In [41]: np.dot(w.transpose(), x.transpose())
Out[41]: 40

In [42]: np.dot(w, x.transpose())
Out[42]: 40

With that information, now let's try to compute the squared length of the vector |w|^2.

For this, we need to transform w to 2D array.

In [51]: wt = w[:, np.newaxis]

In [52]: wt
Out[52]: 
array([[0],
       [1],
       [2],
       [3],
       [4]])

Now, let's compute the squared length (or squared magnitude) of the vector w :

In [53]: np.dot(w, wt)
Out[53]: array([30])

Note that we used w, wt instead of wt, w (like in theoretical linear algebra) because of shape mismatch with the use of np.dot(wt, w). So, we have the squared length of the vector as [30]. Maybe this is one of the ways to distinguish (numpy's interpretation of) row and column vector?

And finally, did I mention that I figured out the way to implement w^T * x ? Yes, I did :

In [58]: wt
Out[58]: 
array([[0],
       [1],
       [2],
       [3],
       [4]])

In [59]: x
Out[59]: array([1, 2, 3, 4, 5])

In [60]: np.dot(x, wt)
Out[60]: array([40])

So, in NumPy, the order of the operands is reversed, as evidenced above, contrary to what we studied in theoretical linear algebra.


P.S. : potential gotchas in numpy

How do ACID and database transactions work?

I slightly modified the printer example to make it more explainable

1 document which had 2 pages content was sent to printer

Transaction - document sent to printer

  • atomicity - printer prints 2 pages of a document or none
  • consistency - printer prints half page and the page gets stuck. The printer restarts itself and prints 2 pages with all content
  • isolation - while there were too many print outs in progress - printer prints the right content of the document
  • durability - while printing, there was a power cut- printer again prints documents without any errors

Hope this helps someone to get the hang of the concept of ACID

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

Is that a faulty solution? (android java)

    // Create MD5 Hash
    MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
    digest.update(s.getBytes());
    byte[] md5sum = digest.digest();
    BigInteger bigInt = new BigInteger(1, md5sum);
    String stringMD5 = bigInt.toString(16);
    // Fill to 32 chars
    stringMD5 = String.format("%32s", stringMD5).replace(' ', '0');
    return stringMD5;

So basically it replaces spaces with 0.

Get decimal portion of a number with JavaScript

If precision matters and you require consistent results, here are a few propositions that will return the decimal part of any number as a string, including the leading "0.". If you need it as a float, just add var f = parseFloat( result ) in the end.

If the decimal part equals zero, "0.0" will be returned. Null, NaN and undefined numbers are not tested.

1. String.split

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = "0." + ( narray.length > 1 ? narray[1] : "0" );

2. String.substring, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = "0." + (nindex > -1 ? nstring.substring(nindex + 1) : "0");

3. Math.floor, Number.toFixed, String.indexOf

var nstring = (n + ""),
    nindex  = nstring.indexOf("."),
    result  = ( nindex > -1 ? (n - Math.floor(n)).toFixed(nstring.length - nindex - 1) : "0.0");

4. Math.floor, Number.toFixed, String.split

var nstring = (n + ""),
    narray  = nstring.split("."),
    result  = (narray.length > 1 ? (n - Math.floor(n)).toFixed(narray[1].length) : "0.0");

Here is a jsPerf link: https://jsperf.com/decpart-of-number/

We can see that proposition #2 is the fastest.

How to remove time portion of date in C# in DateTime object only?

For using by datalist, repeater.. in aspx page:<%# Eval("YourDateString").ToString().Remove(10) %>

Asynchronously load images with jQuery

use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:

$("#img_id").error(function(){
  //$(this).hide();
  //alert("img not loaded");
  //some action you whant here
});

careful - .error() event will not trigger when the src attribute is empty for an image.

Python 101: Can't open file: No such file or directory

Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

How to pass multiple values to single parameter in stored procedure

I think, below procedure help you to what you are looking for.

 CREATE PROCEDURE [dbo].[FindEmployeeRecord]
        @EmployeeID nvarchar(Max)
    AS
    BEGIN
    DECLARE @sqLQuery VARCHAR(MAX)
    Declare @AnswersTempTable Table
    (  
        EmpId int,         
        EmployeeName nvarchar (250),       
        EmployeeAddress nvarchar (250),  
        PostalCode nvarchar (50),
        TelephoneNo nvarchar (50),
        Email nvarchar (250),
        status nvarchar (50),  
        Sex nvarchar (50) 
    )

    Set @sqlQuery =
    'select e.EmpId,e.EmployeeName,e.Email,e.Sex,ed.EmployeeAddress,ed.PostalCode,ed.TelephoneNo,ed.status
    from Employee e
    join EmployeeDetail ed on e.Empid = ed.iEmpID
    where Convert(nvarchar(Max),e.EmpId) in ('+@EmployeeId+')
    order by EmpId'
    Insert into @AnswersTempTable
    exec (@sqlQuery)
    select * from @AnswersTempTable
    END

Performance of Java matrix math libraries?

I'm the main author of jblas and wanted to point out that I've released Version 1.0 in late December 2009. I worked a lot on the packaging, meaning that you can now just download a "fat jar" with ATLAS and JNI libraries for Windows, Linux, Mac OS X, 32 and 64 bit (except for Windows). This way you will get the native performance just by adding the jar file to your classpath. Check it out at http://jblas.org!

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:

this.Controls.Add(this.reportViewer1);

or

[ContainerControl].Controls.Add(this.reportViewer1);

You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

How to show alert message in mvc 4 controller?

Response.Write(@"<script language='javascript'>alert('Message: 
\n" + "Hi!" + " .');</script>");

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

I had similar issues and below is how i fixed it:

  • Restart your PC, when booting up press f10 key to select or open BIOS Settings.
  • Locate and check / enable Virtual Technology-x option under Device Configuration Settings
  • Save changes, system restart.
  • All should be working fine now

Does a finally block always get executed in Java?

That's actually true in any language...finally will always execute before a return statement, no matter where that return is in the method body. If that wasn't the case, the finally block wouldn't have much meaning.

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Do you mean like this?

import string
astr='a(b[c])d'

deleter=string.maketrans('()[]','    ')
print(astr.translate(deleter))
# a b c  d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a

How to convert String to long in Java?

There are a few ways to convert String to long:

1)

long l = Long.parseLong("200"); 
String numberAsString = "1234";
long number = Long.valueOf(numberAsString).longValue();
String numberAsString = "1234";
Long longObject = new Long(numberAsString);
long number = longObject.longValue();

We can shorten to:

String numberAsString = "1234";
long number = new Long(numberAsString).longValue();

Or just

long number = new Long("1234").longValue();
  1. Using Decimal format:
String numberAsString = "1234";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
    long number = decimalFormat.parse(numberAsString).longValue();
    System.out.println("The number is: " + number);
} catch (ParseException e) {
    System.out.println(numberAsString + " is not a valid number.");
}

VB.net Need Text Box to Only Accept Numbers

This worked for me... just clear the textbox completely as non-numeric keys are pressed.

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    If IsNumeric(TextBox2.Text) Then
        'nada
    Else
        TextBox2.Clear()
    End If
End Sub

How to use sbt from behind proxy?

SBT use both HTTP/HTTPS/SFTP/SSH and other kind of connections to a repository. so when behind a proxy, these protocols should be available.

In most simple cases on Windows, you just need to pass proxy parameters options to JVM, like:

java -Dhttp.proxyHost=myproxy -Dhttp.proxyPort=8080

That will do.

But if not, there are few things you should be aware of:

  1. whether if you are making a HTTPS connection to the repository.
  2. whether sever certificates been imported to jre cacerts
  3. whether your proxy would replace your server certificates

to solve first, you should pass https proxy parameter to jvm, like:

java -Dhttps.proxyHost=myproxy -Dhttps.proxyPort=8080 -Djavax.net.ssl.trustStore=${TRUST_STORE_PATH}

to solve the second, you should import the ca. there are a lot of tips.

to solve the third, you maybe could considering using a authentication proxy.

to Simplify the config of SBT, it provide sbtconfig.txt and sbtops in the conf directory, look into it.

Reference:
http://www.scala-sbt.org/0.13/docs/Setup-Notes.html
http://www.scala-sbt.org/1.0/docs/Publishing.html

External VS2013 build error "error MSB4019: The imported project <path> was not found"

Running this in the commandline will fix the problem also. SETX VisualStudioVersion "12.0"

How to set IE11 Document mode to edge as default?

unchecked the "Automatically detect settings" in the Local Area Network Settings (found in "Internet Options" > Connections > LAN Settings.

OracleCommand SQL Parameters Binding

You need to use something like this:

 OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                       WHERE domain_user_name = :userName", db);

More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx

It is advised you use the : character instead of @ for Oracle.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

Identifier is undefined

Are you missing a function declaration?

void ac_search(uint num_patterns, uint pattern_length, const char *patterns, 
               uint num_records, uint record_length, const char *records, int *matches, Node* trie);

Add it just before your implementation of ac_benchmark_search.

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

Indentation Error in Python

In doubt change your editor to make tabs and spaces visible. It is also a very good idea to have the editor resolve all tabs to 4 spaces.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow

So i used:

stage ('Starting ART job') {
    build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}

make script execution to unlimited

You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:

ini_set('max_execution_time', 0);

Refer to the PHP documentation of max_execution_time

Note that:

set_time_limit(0);

will have the same effect.

Writing files in Node.js

I know the question asked about "write" but in a more general sense "append" might be useful in some cases as it is easy to use in a loop to add text to a file (whether the file exists or not). Use a "\n" if you want to add lines eg:

var fs = require('fs');
for (var i=0; i<10; i++){
    fs.appendFileSync("junk.csv", "Line:"+i+"\n");
}

When saving, how can you check if a field has changed?

Since Django 1.8 released, you can use from_db classmethod to cache old value of remote_image. Then in save method you can compare old and new value of field to check if the value has changed.

@classmethod
def from_db(cls, db, field_names, values):
    new = super(Alias, cls).from_db(db, field_names, values)
    # cache value went from the base
    new._loaded_remote_image = values[field_names.index('remote_image')]
    return new

def save(self, force_insert=False, force_update=False, using=None,
         update_fields=None):
    if (self._state.adding and self.remote_image) or \
        (not self._state.adding and self._loaded_remote_image != self.remote_image):
        # If it is first save and there is no cached remote_image but there is new one, 
        # or the value of remote_image has changed - do your stuff!

Count rows with not empty value

Make another column that determines if the referenced cell is blank using the function "CountBlank". Then use count on the values created in the new "CountBlank" column.

Get Android Phone Model programmatically

You can get the phone device name from the

BluetoothAdapter

In case phone doesn't support Bluetooth, then you have to construct the device name from

android.os.Build class

Here is the sample code to get the phone device name.

public String getPhoneDeviceName() {  
        String name=null;
        // Try to take Bluetooth name
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            name = adapter.getName();
        }

        // If not found, use MODEL name
        if (TextUtils.isEmpty(name)) {
            String manufacturer = Build.MANUFACTURER;
            String model = Build.MODEL;
            if (model.startsWith(manufacturer)) {
                name = model;
            } else {
                name = manufacturer + " " + model;
            }
        } 
        return name;
}

AngularJS - convert dates in controller

create a filter.js and you can make this as reusable

angular.module('yourmodule').filter('date', function($filter)
{
    return function(input)
    {
        if(input == null){ return ""; }
        var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
        return _date.toUpperCase();
    };
});

view

<span>{{ d.time | date }}</span>

or in controller

var filterdatetime = $filter('date')( yourdate );

Date filtering and formatting in Angular js.

Media query to detect if device is touchscreen

There is actually a media query for that:

@media (hover: none) { … }

Apart from Firefox, it's fairly well supported. Safari and Chrome being the most common browsers on mobile devices, it might suffice untill greater adoption.

Including one C source file in another?

is it ok? yes, it will compile

is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file