Programs & Examples On #Net ssh

A pure-Ruby implementation of the SSH2 client protocol. It allows you to write programs that invoke and interact with processes on remote servers, via SSH2.

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

I think rake must be preinstalled if you want work with bundler. Try to install rake via 'gem install' and then run 'bundle install' again:

gem install rake && bundle install

If you are using rvm ( http://rvm.io ) rake is installed by default...

Could not create the Java virtual machine

Set the JVM memory:

export _JAVA_OPTIONS=-Xmx512M

Double % formatting question for printf in Java

%d is for integers use %f instead, it works for both float and double types:

double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000

Word count from a txt file program

import sys
file=open(sys.argv[1],"r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for key in wordcount.keys():
  print ("%s %s " %(key , wordcount[key]))
file.close();

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4.x the log level is configured a bit different than in Rails 3.x

Add this to config/environment/test.rb

# Enable stdout logger
config.logger = Logger.new(STDOUT)

# Set log level
config.log_level = :ERROR

The logger level is set on the logger instance from config.log_level at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70

Environment variable

As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:

# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")

And then running tests from shell:

# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test

# Log level :ERROR
$ rake test

What are the differences between LinearLayout, RelativeLayout, and AbsoluteLayout?

Definitions:

  • Frame Layout: This is designed to block out an area on the screen to display a single item.
  • Linear Layout: A layout that arranges its children in a single column or a single row.
  • Relative Layout: This layout is a view group that displays child views in relative positions.
  • Table Layout: A layout that arranges its children into rows and columns.

More Information:

FrameLayout

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.

Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).

RelativeLayout

A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.

(Current docs here)

TableLayout

A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column.


Note: Absolute Layout is deprecated.

Typescript - multidimensional array initialization

You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.

The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.

As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.

class Something {
    private things: Thing[][];

    constructor() {
        this.things = [];

        for(var i: number = 0; i < 10; i++) {
            this.things[i] = [];
            for(var j: number = 0; j< 10; j++) {
                this.things[i][j] = new Thing();
            }
        }
    }
}

Detect key input in Python

Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

  1. define an event_handle method
  2. pick an event(event_sequence) that fits your case from an events list

When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def event_handle(event):
    # Replace the window's title with event.type: input key
    root.title("{}: {}".format(str(event.type), event.keysym))


if __name__ == '__main__':
    root = tk.Tk()
    event_sequence = '<KeyPress>'
    root.bind(event_sequence, event_handle)
    root.bind('<KeyRelease>', event_handle)
    root.mainloop()

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

The difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.

For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).

Angularjs loading screen on ajax request

I built on @DavidLin's answer a little to simplify it - removing any dependency on jQuery in the directive. I can confirm this works as I use it in a production application

function AjaxLoadingOverlay($http) {

    return {
        restrict: 'A',
        link: function ($scope, $element, $attributes) {

            $scope.loadingOverlay = false;

            $scope.isLoading = function () {
                return $http.pendingRequests.length > 0;
            };

            $scope.$watch($scope.isLoading, function (isLoading) {
                $scope.loadingOverlay = isLoading;
            });
        }
    };
}   

I use a ng-show instead of a jQuery call to hide/show the <div>.

Here's the <div> which I placed just below the opening <body> tag:

<div ajax-loading-overlay class="loading-overlay" ng-show="loadingOverlay">
    <img src="Resources/Images/LoadingAnimation.gif" />
</div>

And here's the CSS that provides the overlay to block UI while a $http call is being made:

.loading-overlay {
    position: fixed;
    z-index: 999;
    height: 2em;
    width: 2em;
    overflow: show;
    margin: auto;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

.loading-overlay:before {
    content: '';
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.3);
}

/* :not(:required) hides these rules from IE9 and below */
.loading-overlay:not(:required) {
    font: 0/0 a;
    color: transparent;
    text-shadow: none;
    background-color: transparent;
    border: 0;
}

CSS credit goes to @Steve Seeger's - his post: https://stackoverflow.com/a/35470281/335545

SQL Query to concatenate column values from multiple rows in Oracle

There's also an XMLAGG function, which works on versions prior to 11.2. Because WM_CONCAT is undocumented and unsupported by Oracle, it's recommended not to use it in production system.

With XMLAGG you can do the following:

SELECT XMLAGG(XMLELEMENT(E,ename||',')).EXTRACT('//text()') "Result" 
FROM employee_names

What this does is

  • put the values of the ename column (concatenated with a comma) from the employee_names table in an xml element (with tag E)
  • extract the text of this
  • aggregate the xml (concatenate it)
  • call the resulting column "Result"

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

One minor thing, which wasted my time.

Put the conditions(if comparing using " = ", " != ") in parenthesis, failing to do so also raises this exception. This will work

df[(some condition) conditional operator (some conditions)]

This will not

df[some condition conditional-operator some condition]

Centering elements in jQuery Mobile

Adjust as your requirement

   .ui-btn{
      margin:0.5em 10px;
    }

Is there a max array length limit in C++?

Nobody mentioned the limit on the size of the stack frame.

There are two places memory can be allocated:

  • On the heap (dynamically allocated memory).
    The size limit here is a combination of available hardware and the OS's ability to simulate space by using other devices to temporarily store unused data (i.e. move pages to hard disk).
  • On the stack (Locally declared variables).
    The size limit here is compiler defined (with possible hardware limits). If you read the compiler documentation you can often tweak this size.

Thus if you allocate an array dynamically (the limit is large and described in detail by other posts.

int* a1 = new int[SIZE];  // SIZE limited only by OS/Hardware

Alternatively if the array is allocated on the stack then you are limited by the size of the stack frame. N.B. vectors and other containers have a small presence in the stack but usually the bulk of the data will be on the heap.

int a2[SIZE]; // SIZE limited by COMPILER to the size of the stack frame

How to install gdb (debugger) in Mac OSX El Capitan?

Here's a blog post explains it very well:

http://panks.me/posts/2013/11/install-gdb-on-os-x-mavericks-from-source/

And the way I get it working:

  1. Create a coding signing certificate via KeyChain Access:

    1.1 From the Menu, select KeyChain Access > Certificate Assistant > Create a Certificate...

    1.2 Follow the wizard to create a certificate and let's name it gdb-cert, the Identity Type is Self Signed Root, and the Certificate Type is Code Signing and select the Let me override defaults.

    1.3 Click several times on Continue until you get to the Specify a Location For The Certificate screen, then set Keychain to System.

  2. Install gdb via Homebrew: brew install gdb

  3. Restart taskgated: sudo killall taskgated && exit

  4. Reopen a Terminal window and type sudo codesign -vfs gdb-cert /usr/local/bin/gdb

How to redirect all HTTP requests to HTTPS

If you want to do it from the tomcat server follow the below steps

In a standalone Apache Tomcat (8.5.x) HTTP Server, how can configure it so if a user types www.domain.com, they will be automatically forwarded to https(www.domain.com) site.

The 2 step method of including the following in your [Tomcat_base]/conf/web.xml before the closing tag

step 1: 
<security-constraint>
<web-resource-collection>
<web-resource-name>HTTPSOnly</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

and setting the [Tomcat_base]/conf/server.xml connector settings:

step 2:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="443"/>
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="[keystorelocation]" type="RSA" />
</SSLHostConfig>
</Connector>

Note: If you already did the https configuration and trying to redirect do step 1 only.

Excel VBA App stops spontaneously with message "Code execution has been halted"

This problem comes from a strange quirk within Office/Windows.

After developing the same piece of VBA code and running it hundreds of times (literally) over the last couple days I ran into this problem just now. The only thing that has been different is that just prior to experiencing this perplexing problem I accidentally ended the execution of the VBA code with an unorthodox method.

I cleaned out all temp files, rebooted, etc... When I ran the code again after all of this I still got the issue - before I entered the first loop. It makes sense that "press "Debug" button in the popup, then press twice [Ctrl+Break] and after this can continue without stops" because something in the combination of Office/Windows has not released the execution. It is stuck.

The redundant Ctrl+Break action probably resolves the lingering execution.

Node.js - use of module.exports as a constructor

CommonJS modules allow two ways to define exported properties. In either case you are returning an Object/Function. Because functions are first class citizens in JavaScript they to can act just like Objects (technically they are Objects). That said your question about using the new keywords has a simple answer: Yes. I'll illustrate...

Module exports

You can either use the exports variable provided to attach properties to it. Once required in another module those assign properties become available. Or you can assign an object to the module.exports property. In either case what is returned by require() is a reference to the value of module.exports.

A pseudo-code example of how a module is defined:

var theModule = {
  exports: {}
};

(function(module, exports, require) {

  // Your module code goes here

})(theModule, theModule.exports, theRequireFunction);

In the example above module.exports and exports are the same object. The cool part is that you don't see any of that in your CommonJS modules as the whole system takes care of that for you all you need to know is there is a module object with an exports property and an exports variable that points to the same thing the module.exports does.

Require with constructors

Since you can attach a function directly to module.exports you can essentially return a function and like any function it could be managed as a constructor (That's in italics since the only difference between a function and a constructor in JavaScript is how you intend to use it. Technically there is no difference.)

So the following is perfectly good code and I personally encourage it:

// My module
function MyObject(bar) {
  this.bar = bar;
}

MyObject.prototype.foo = function foo() {
  console.log(this.bar);
};

module.exports = MyObject;

// In another module:
var MyObjectOrSomeCleverName = require("./my_object.js");
var my_obj_instance = new MyObjectOrSomeCleverName("foobar");
my_obj_instance.foo(); // => "foobar"

Require for non-constructors

Same thing goes for non-constructor like functions:

// My Module
exports.someFunction = function someFunction(msg) {
  console.log(msg);
}

// In another module
var MyModule = require("./my_module.js");
MyModule.someFunction("foobar"); // => "foobar"

Java method: Finding object in array list given a known attribute value

A while applies to the expression or block after the while.

You dont have a block, so your while ends with the expression dog=al.get(i);

while(dog.getId()!=id && i<length)
                dog=al.get(i);

Everything after that happens only once.

There's no reason to new up a Dog, as you're never using the dog you new'd up; you immediately assign a Dog from the array to your dog reference.

And if you need to get a value for a key, you should use a Map, not an Array.

Edit: this was donwmodded why??

Comment from OP:

One further question with regards to not having to make a new instance of a Dog. If I am just taking out copies of the objects from the array list, how can I then take it out from the array list without having an object in which I put it? I just noticed as well that I didn't bracket the while-loop.

A Java reference and the object it refers to are different things. They're very much like a C++ reference and object, though a Java reference can be re-pointed like a C++ pointer.

The upshot is that Dog dog; or Dog dog = null gives you a reference that points to no object. new Dog() creates an object that can be pointed to.

Following that with a dog = al.get(i) means that the reference now points to the dog reference returned by al.get(i). Understand, in Java, objects are never returned, only references to objects (which are addresses of the object in memory).

The pointer/reference/address of the Dog you newed up is now lost, as no code refers to it, as the referent was replaced with the referent you got from al.get(). Eventually the Java garbage collector will destroy that object; in C++ you'd have "leaked" the memory.

The upshot is that you do need to create a variable that can refer to a Dog; you don't need to create a Dog with new.

(In truth you don't need to create a reference, as what you really ought to be doing is returning what a Map returns from its get() function. If the Map isn't parametrized on Dog, like this: Map<Dog>, then you'll need to cast the return from get, but you won't need a reference: return (Dog) map.get(id); or if the Map is parameterized, return map.get(id). And that one line is your whole function, and it'll be faster than iterating an array for most cases.)

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The general approach to write to any stream (not only MemoryStream) is to use BinaryWriter:

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

How to undo a SQL Server UPDATE query?

A non-committed transaction can be reverted by issuing the command ROLLBACK

But if you are running in auto-commit mode there is nothing you can do....

HTML-Tooltip position relative to mouse pointer

One way to do this without JS is to use the hover action to reveal a HTML element that is otherwise hidden, see this codepen:

http://codepen.io/c0un7z3r0/pen/LZWXEw

Note that the span that contains the tooltip content is relative to the parent li. The magic is here:

ul#list_of_thrones li > span{
  display:none;
}
ul#list_of_thrones li:hover > span{
  position: absolute;
  display:block;
  ...
}

As you can see, the span is hidden unless the listitem is hovered over, thus revealing the span element, the span can contain as much html as you need. In the codepen attached I have also used a :after element for the arrow but that of course is entirely optional and has only been included in this example for cosmetic purposes.

I hope this helps, I felt compelled to post as all the other answers included JS solutions but the OP asked for a HTML/CSS only solution.

Convert int (number) to string with leading zeros? (4 digits)

Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.

To get the string representation using at least 4 digits:

int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"

How to switch between hide and view password

You can SHOW/HIDE password using this below code:

XML CODE:

<EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="14dp"
        android:ems="10"
        android:inputType="textPassword" >
        <requestFocus />
    </EditText>
    <CheckBox
        android:id="@+id/cbShowPwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/etPassword"
        android:layout_below="@+id/etPassword"
        android:text="@string/show_pwd" />

JAVA CODE:

EditText mEtPwd;
CheckBox mCbShowPwd;


mEtPwd = (EditText) findViewById(R.id.etPassword);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);

mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // checkbox status is changed from uncheck to checked.
        if (!isChecked) {
            // show password
            mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            // hide password
            mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
    }
});

Sort array of objects by string property value

It is also possible to make a dynamic sorting function when programming in TypeScript, but the types become more tricky in this case.

function sortByKey<O>(key: keyof O, decending: boolean = false): (a: O, b: O) => number {
    const order = decending ? -1 : 1;
    return (a, b): number => {
        const valA = a[key];
        const valB = b[key];
        if (valA < valB) {
            return -order;
        } else if (valA > valB) {
            return order;
        } else {
            return 0;
        }
    }
}

This can be used in TypeScript as the following:

const test = [
    {
        id: 0,
    },
    {
        id: 2,
    }
]

test.sort(sortByKey('id')) // OK
test.sort(sortByKey('id1')) // ERROR
test.sort(sortByKey('')) // ERROR

How to determine whether an object has a given property in JavaScript

You can trim that up a bit like this:

if ( x.y !== undefined ) ...

How do I tell what type of value is in a Perl variable?

ref():

Perl provides the ref() function so that you can check the reference type before dereferencing a reference...

By using the ref() function you can protect program code that dereferences variables from producing errors when the wrong type of reference is used...

Convert PEM to PPK file format

I had the same issue with PuttyGen not wanting to import an openSSH private key. I tried everything and what I found out was the old version of PuttyGen did not support importing OpenSSH. Once I downloaded the latest Putty, puttygen then allowed it to import the openssh private key just fine. I now have a hole in the side of my desk for pounding my head against it for the past hour.

How do you copy and paste into Git Bash

This is suggested by the github help page:

clip < filename

this copies the contents of filename to the clipboard and is useful for doing things like copying your id_rsa.pub to a web form.

Select element based on multiple classes

You can use these solutions :

CSS rules applies to all tags that have following two classes :

.left.ui-class-selector {
    /*style here*/
}

CSS rules applies to all tags that have <li> with following two classes :

li.left.ui-class-selector {
   /*style here*/
}

jQuery solution :

$("li.left.ui-class-selector").css("color", "red");

Javascript solution :

document.querySelector("li.left.ui-class-selector").style.color = "red";

Read file from aws s3 bucket using node fs

here is the example which i used to retrive and parse json data from s3.

    var params = {Bucket: BUCKET_NAME, Key: KEY_NAME};
    new AWS.S3().getObject(params, function(err, json_data)
    {
      if (!err) {
        var json = JSON.parse(new Buffer(json_data.Body).toString("utf8"));

       // PROCESS JSON DATA
           ......
     }
   });

Javascript array sort and unique

How about:

array.sort().filter(function(elem, index, arr) {
  return index == arr.length - 1 || arr[index + 1] != elem
})

This is similar to @loostro answer but instead of using indexOf which will reiterate the array for each element to verify that is the first found, it just checks that the next element is different than the current.

.keyCode vs. .which

Note: The answer below was written in 2010. Here many years later, both keyCode and which are deprecated in favor of key (for the logical key) and code (for the physical placement of the key). But note that IE doesn't support code, and its support for key is based on an older version of the spec so isn't quite correct. As I write this, the current Edge based on EdgeHTML and Chakra doesn't support code either, but Microsoft is rolling out its Blink- and V8- based replacement for Edge, which presumably does/will.


Some browsers use keyCode, others use which.

If you're using jQuery, you can reliably use which as jQuery standardizes things; More here.

If you're not using jQuery, you can do this:

var key = 'which' in e ? e.which : e.keyCode;

Or alternatively:

var key = e.which || e.keyCode || 0;

...which handles the possibility that e.which might be 0 (by restoring that 0 at the end, using JavaScript's curiously-powerful || operator).

Error when trying vagrant up

well, actually you have to do:

vagrant up laravel/homestead

because according to homestead walkthrough you've just downloaded it: http://laravel.com/docs/5.0/homestead by:

vagrant box add laravel/homestead

so you have to launch the box you mean to use - not some random ubuntu image ;)

Get number of digits with JavaScript

Here is my solution. It works with positive and negative numbers. Hope this helps

function findDigitAmount(num) {

   var positiveNumber = Math.sign(num) * num;
   var lengthNumber = positiveNumber.toString();

 return lengthNumber.length;
}


(findDigitAmount(-96456431);    // 8
(findDigitAmount(1524):         // 4

Is there a way to provide named parameters in a function call in JavaScript?

Coming from Python this bugged me. I wrote a simple wrapper/Proxy for node that will accept both positional and keyword objects.

https://github.com/vinces1979/node-def/blob/master/README.md

How to fetch all Git branches

|?????????????fetch/clone?????????????   |????????????checkout???????????   
|???????????????????????????????????pull?????????????????????????????????
Remote repository (`origin`) <=> Local repository <=> Index <=> Workspace
?_________________push_______________|   ?____commit____|  ?____add_____| 

# ???????????? ? ????
# fetch all remote repository branch meta ? local repository
git remote set-branches origin '*'
git fetch -v

# ?????????????
# fetch all remote repository branch data ? local repository
git branch -r | grep -v '\->' | while read remote; do git branch "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

Java - Change int to ascii

There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:

private static String toASCII(int value) {
    int length = 4;
    StringBuilder builder = new StringBuilder(length);
    for (int i = length - 1; i >= 0; i--) {
        builder.append((char) ((value >> (8 * i)) & 0xFF));
    }
    return builder.toString();
}

For example, the ASCII text for "TEST" can be represented as the byte array:

byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };

Then you could do the following:

int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"

...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:

  • Verbose - Show all log messages (the default).
  • Debug - Show debug log messages that are useful during development only, as well as the message levels lower in this list.
  • Info - Show expected log messages for regular usage, as well as the message levels lower in this list.
  • Warn - Show possible issues that are not yet errors, as well as the message levels lower in this list.
  • Error - Show issues that have caused errors, as well as the message level lower in this list.
  • Assert - Show issues that the developer expects should never happen.

Return list from async/await method

In addition to @takemyoxygen's answer the convention of having a function name that ends in Async is that this function is truly asynchronous. I.e. it does not start a new thread and it doesn't simply call Task.Run. If that is all the code that is in your function, it will be better to remove it completely and simply have:

List<Item> list = await Task.Run(() => manager.GetList());

Send password when using scp to copy files from one server to another

Firts as mentioned by David, we need to set up public/private key.

Then using below command had worked for me, means it didn't prompt me for password as we are passing private key in the command using -i option

scp -i path/to/private_key path/to/local/file remoteUserId@remoteHost:/path/to/remote/folder

Here path/to/private_key is private key file which we generated while setting up public/private key.

Remove trailing zeros

try this code:

string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');

Round double in two decimal places in C#?

Use Math.Round

value = Math.Round(48.485, 2);

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

  • pyenv - manages different python versions,
  • all others - create virtual environment (which has isolated python version and installed "requirements"),

pipenv want combine all, in addition to previous it installs "requirements" (into the active virtual environment or create its own if none is active)

So maybe you will be happy with pipenv only.

But I use: pyenv + pyenv-virtualenvwrapper, + pipenv (pipenv for installing requirements only).

In Debian:

  1. apt install libffi-dev

  2. install pyenv based on https://www.tecmint.com/pyenv-install-and-manage-multiple-python-versions-in-linux/, but..

  3. .. but instead of pyenv-virtualenv install pyenv-virtualenvwrapper (which can be standalone library or pyenv plugin, here the 2nd option):

    pyenv install 3.9.0

    git clone https://github.com/pyenv/pyenv-virtualenvwrapper.git $(pyenv root)/plugins/pyenv-virtualenvwrapper

    into ~/.bashrc add: export $VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"

    source ~/.bashrc

    pyenv virtualenvwrapper

Then create virtual environments for your projects (workingdir must exist):

pyenv local 3.9.0  # to prevent 'interpreter not found' in mkvirtualenv
python -m pip install --upgrade pip setuptools wheel
mkvirtualenv <venvname> -p python3.9 -a <workingdir>

and switch between projects:

workon <venvname>
python -m pip install --upgrade pip setuptools wheel pipenv

Inside a project I have the file requirements.txt, without fixing the versions inside (if some version limitation is not neccessary). You have 2 possible tools to install them into the current virtual environment: pip-tools or pipenv. Lets say you will use pipenv:

pipenv install -r requirements.txt

this will create Pipfile and Pipfile.lock files, fixed versions are in the 2nd one. If you want reinstall somewhere exactly same versions then (Pipfile.lock must be present):

pipenv install

Remember that Pipfile.lock is related to some Python version and need to be recreated if you use a different one.

As you see I write requirements.txt. This has some problems: You must remove a removed package from Pipfile too. So writing Pipfile directly is probably better.

So you can see I use pipenv very poorly. Maybe if you will use it well, it can replace everything?

EDIT 2021.01: I have changed my stack to: pyenv + pyenv-virtualenvwrapper + poetry. Ie. I use no apt or pip installation of virtualenv or virtualenvwrapper, and instead I install pyenv's plugin pyenv-virtualenvwrapper. This is easier way.

Poetry is great for me:

poetry add <package>   # install single package
poetry remove <package>
poetry install   # if you remove poetry.lock poetry will re-calculate versions

How can you encode a string to Base64 in JavaScript?

Sunny's code is great except it breaks in IE7 because of references to "this". Fixed by replacing such references with "Base64":

var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
        Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = Base64._keyStr.indexOf(input.charAt(i++));
        enc2 = Base64._keyStr.indexOf(input.charAt(i++));
        enc3 = Base64._keyStr.indexOf(input.charAt(i++));
        enc4 = Base64._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }
    return string;
}
}

C# "must declare a body because it is not marked abstract, extern, or partial"

You cannot provide your own implementation for the setter when using automatic properties. In other words, you should either do:

public int Hour { get;set;} // Automatic property, no implementation

or provide your own implementation for both the getter and setter, which is what you want judging from your example:

public int Hour  
{ 
    get { return hour; } 
    set 
    {
        if (value < MIN_HOUR)
        {
            hour = 0;
            MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
                    "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
                //take the modulus to ensure always less than 24 hours
                //works even if the value is already within range, or value equal to 24
                hour = value % MAX_HOUR;
        }
     }
}

Reactjs convert html string to jsx

I recommend using Interweave created by milesj. Its a phenomenal library that makes use of a number if ingenious techniques to parse and safely insert HTML into the DOM.

Interweave is a react library to safely render HTML, filter attributes, autowrap text with matchers, render emoji characters, and much more.

  • Interweave is a robust React library that can:
    • Safely render HTML without using dangerouslySetInnerHTML.
    • Safely strip HTML tags.
    • Automatic XSS and injection protection.
    • Clean HTML attributes using filters.
    • Interpolate components using matchers.
    • Autolink URLs, IPs, emails, and hashtags.
    • Render Emoji and emoticon characters.
    • And much more!

Usage Example:

import React from 'react';
import { Markup } from 'interweave';

const articleContent = "<p><b>Lorem ipsum dolor laboriosam.</b> </p><p>Facere debitis impedit doloremque eveniet eligendi reiciendis <u>ratione obcaecati repellendus</u> culpa? Blanditiis enim cum tenetur non rem, atque, earum quis, reprehenderit accusantium iure quas beatae.</p><p>Lorem ipsum dolor sit amet <a href='#testLink'>this is a link, click me</a> Sunt ducimus corrupti? Eveniet velit numquam deleniti, delectus  <ol><li>reiciendis ratione obcaecati</li><li>repellendus culpa? Blanditiis enim</li><li>cum tenetur non rem, atque, earum quis,</li></ol>reprehenderit accusantium iure quas beatae.</p>"

<Markup content={articleContent} /> // this will take the articleContent string and convert it to HTML markup. See: https://milesj.gitbook.io/interweave


//to install package using npm, execute the command
npm install interweave

ASP.NET Button to redirect to another page

<button type ="button" onclick="location.href='@Url.Action("viewname","Controllername")'"> Button name</button>

for e.g ,

<button type="button" onclick="location.href='@Url.Action("register","Home")'">Register</button>

Convert SQL Server result set into string

The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...

ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286

original query...

SELECT StudentId FROM Student WHERE condition = xyz

original result set...

StudentId
1236
7656
8990

new query w/ concat...

SELECT group_concat(concat_ws(',', StudentId) separator '; ') 
FROM Student 
WHERE condition = xyz

concat string result set...

StudentId
1236; 7656; 8990

note: change the 'separator' to whatever you would like

GLHF!

Recover SVN password from local cache

In ~/.subversion/auth/svn.simple/ you should find a file with a long hexadecimal name. The password is in there in plaintext.

If there is more than one file you'll need to find that one that references the server you need the password for.

Spring MVC Multipart Request with JSON

This is how I implemented Spring MVC Multipart Request with JSON Data.

Multipart Request with JSON Data (also called Mixed Multipart):

Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.

Java Snippet:

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

Front End (JavaScript) Snippet:

  1. Create a FormData object.

  2. Append the file to the FormData object using one of the below steps.

    1. If the file has been uploaded using an input element of type "file", then append it to the FormData object. formData.append("file", document.forms[formName].file.files[0]);
    2. Directly append the file to the FormData object. formData.append("file", myFile, "myfile.txt"); OR formData.append("file", myBob, "myfile.txt");
  3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.

  4. Send the request to the server.

  5. Request Details:
    Content-Type: undefined. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript Code:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

Request Details:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

Allowed memory size of 536870912 bytes exhausted in Laravel

I had the same problem. No matter how much I was increasing memory_limit (even tried 4GB) I was getting the same error, until I figured out it was because of wrong database credentials setted up in .env file

Adding items to end of linked list

class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d ;
        next = n ;
       }

   public static Node addLast(Node header, Object x) {
       // save the reference to the header so we can return it.
       Node ret = header;

       // check base case, header is null.
       if (header == null) {
           return new Node(x, null);
       }

       // loop until we find the end of the list
       while ((header.next != null)) {
           header = header.next;
       }

       // set the new node to the Object x, next will be null.
       header.next = new Node(x, null);
       return ret;
   }
}

How can I define fieldset border color?

It does appear red on Firefox and IE 8. But perhaps you need to change the border-style too.

_x000D_
_x000D_
.field_set{_x000D_
  border-color: #F00;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<fieldset class="field_set">_x000D_
  <legend>box</legend>_x000D_
  <table width="100%" border="0" cellspacing="0" cellpadding="0">_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

alt text

what is the use of Eval() in asp.net

Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.

It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.

How can I add items to an empty set in python

When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

Javascript to convert UTC to local time

You could take a look at date-and-time api for easily date manipulation.

_x000D_
_x000D_
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);_x000D_
console.log(now);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
_x000D_
_x000D_
_x000D_

Oracle: not a valid month

1.

To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE

is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...

SQL> select sysdate from dual;

SYSDATE
---------
26-SEP-12

Which means my session's setting is DD-Mon-YY

SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;

TO_CHAR(SY
----------
09/26/2012


SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;

TO_DATE(T
---------
26-SEP-12

2.

More importantly, Why are you converting to char and then to date, instead of directly comparing

MaxDate = REP_DATE

If you want to ignore the time component in MaxDate before comparision, you should use..

trunc(MaxDate ) = rep_date

instead.

==Update : based on updated question.

Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00

I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.

If it is a running system and you have no control over repdate, you could try this.

trunc(rep_date) = trunc(maxdate) and 
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')

Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.

findViewByID returns null

For me I had two xml layouts for the same activity - one in portrait mode and one in landscape. Of course I had changed the id of an object in the landscape xml but had forgotten to make the same change in the portrait version. Make sure if you change one you do the same to the other xml or you will not get an error until you run/debug it and it can't find the id you didn't change. Oh dumb mistakes, why must you punish me so?

Best method to download image from url in Android

Try this code to download an image from a URL on Android:

DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);

Numpy AttributeError: 'float' object has no attribute 'exp'

You convert type np.dot(X, T) to float32 like this:

z=np.array(np.dot(X, T),dtype=np.float32)

def sigmoid(X, T):
    return (1.0 / (1.0 + np.exp(-z)))

Hopefully it will finally work!

Mosaic Grid gallery with dynamic sized images

I suggest Freewall. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.

Home page and document: also found here.

How to save S3 object to a file using boto3

# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}

import boto3
import io

s3 = boto3.resource('s3')

obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)

# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))

print(new_dict['status']) 
# Should print "Error"

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library

getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();

or

getActivity().getFragmentManager().beginTransaction().remove(this).commit();

otherwise.

In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...

Getting list of parameter names inside python function

locals() returns a dictionary with local names:

def func(a,b,c):
    print(locals().keys())

prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.

Convert ArrayList<String> to String[] array

The correct way to do this is:

String[] stockArr = stock_list.toArray(new String[stock_list.size()]);

I'd like to add to the other great answers here and explain how you could have used the Javadocs to answer your question.

The Javadoc for toArray() (no arguments) is here. As you can see, this method returns an Object[] and not String[] which is an array of the runtime type of your list:

public Object[] toArray()

Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array will be "safe" in that no references to it are maintained by the collection. (In other words, this method must allocate a new array even if the collection is backed by an Array). The caller is thus free to modify the returned array.

Right below that method, though, is the Javadoc for toArray(T[] a). As you can see, this method returns a T[] where T is the type of the array you pass in. At first this seems like what you're looking for, but it's unclear exactly why you're passing in an array (are you adding to it, using it for just the type, etc). The documentation makes it clear that the purpose of the passed array is essentially to define the type of array to return (which is exactly your use case):

public <T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. If the collection fits in the specified array with room to spare (i.e., the array has more elements than the collection), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the collection only if the caller knows that the collection does not contain any null elements.)

If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

This implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). Then, it iterates over the collection, storing each object reference in the next consecutive element of the array, starting with element 0. If the array is larger than the collection, a null is stored in the first location after the end of the collection.

Of course, an understanding of generics (as described in the other answers) is required to really understand the difference between these two methods. Nevertheless, if you first go to the Javadocs, you will usually find your answer and then see for yourself what else you need to learn (if you really do).

Also note that reading the Javadocs here helps you to understand what the structure of the array you pass in should be. Though it may not really practically matter, you should not pass in an empty array like this:

String [] stockArr = stockList.toArray(new String[0]);  

Because, from the doc, this implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). There's no need for the extra overhead in creating a new array when you could easily pass in the size.

As is usually the case, the Javadocs provide you with a wealth of information and direction.

Hey wait a minute, what's reflection?

How do you find out which version of GTK+ is installed on Ubuntu?

get GTK3 version:

dpkg -s libgtk-3-0|grep '^Version'

or just version number

dpkg -s libgtk-3-0|grep '^Version' | cut -d' ' -f2-

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

"static const" vs "#define" vs "enum"

In C, specifically? In C the correct answer is: use #define (or, if appropriate, enum)

While it is beneficial to have the scoping and typing properties of a const object, in reality const objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.

So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int object as a case label (while a macro will work). You can't use a const int object as a bit-field width (while a macro will work). In C89/90 you can't use a const object to specify an array size (while a macro will work). Even in C99 you can't use a const object to specify an array size when you need a non-VLA array.

If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define in C. And don't forget another alternative, that produces true constants in C - enum.

In C++ const objects are true constants, so in C++ it is almost always better to prefer the const variant (no need for explicit static in C++ though).

Delete cookie by name?

I'm not really sure if that was the situation with Roundcube version from May '12, but for current one the answer is that you can't delete roundcube_sessauth cookie from JavaScript, as it is marked as HttpOnly. And this means it's not accessible from JS client side code and can be removed only by server side script or by direct user action (via some browser mechanics like integrated debugger or some plugin).

What is the meaning of "Failed building wheel for X" in pip install?

It might be helpful to address this question from a package deployment perspective.

There are many tutorials out there that explain how to publish a package to PyPi. Below are a couple I have used;

medium
real python

My experience is that most of these tutorials only have you use the .tar of the source, not a wheel. Thus, when installing packages created using these tutorials, I've received the "Failed to build wheel" error.

I later found the link on PyPi to the Python Software Foundation's docs PSF Docs. I discovered that their setup and build process is slightly different, and does indeed included building a wheel file.

After using the officially documented method, I no longer received the error when installing my packages.

So, the error might simply be a matter of how the developer packaged and deployed the project. None of us were born knowing how to use PyPi, and if they happened upon the wrong tutorial -- well, you can fill in the blanks.

I'm sure that is not the only reason for the error, but I'm willing to bet that is a major reason for it.

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

git pull remote branch cannot find remote ref

This is because your remote branch name is "DownloadManager“, I guess when you checkout your branch, you give this branch a new name "downloadmanager".

But this is just your local name, not remote ref name.

mvn clean install vs. deploy vs. release

The clean, install and deploy phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.

mvn clean install

This command invokes the clean phase and then the install phase sequentially:

  • clean: removes files generated at build-time in a project's directory (target by default)
  • install: installs the package into the local repository, for use as a dependency in other projects locally.

mvn deploy

This command invokes the deploy phase:

  • deploy: copies the final package to the remote repository for sharing with other developers and projects.

mvn release

This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare and perform. As documented:

Preparing a release goes through the following release phases:

  • Check that there are no uncommitted changes in the sources
  • Check that there are no SNAPSHOT dependencies
  • Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
  • Transform the SCM information in the POM to include the final destination of the tag
  • Run the project tests against the modified POMs to confirm everything is in working order
  • Commit the modified POMs
  • Tag the code in the SCM with a version name (this will be prompted for)
  • Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
  • Commit the modified POMs

And then:

Performing a release runs the following release phases:

  • Checkout from an SCM URL with optional tag
  • Run the predefined Maven goals to release the project (by default, deploy site-deploy)

See also

Setting size for icon in CSS

None of those work for me.

.fa-volume-down {
    color: white;
    width: 50% !important;
    height: 50% !important;
    margin-top: 8%;
    margin-left: 7.5%;
    font-size: 1em;
    background-size: 120%;
}

How to change Java version used by TOMCAT?

In Eclipse it is very easy to point Tomcat to a new JVM (in this example JRE6). My problem was I couldn't find where to do it. Here is the trick:

  1. On the ECLIPSE top menu FILE pull down tab, select NEW, -->Other
  2. ...on the New Server: Select A Wizard window, select: Server-> Server... click NEXT
  3. . on the New Server: Define a New Server window, select Apache> Tomcat 7 Server
  4. ..now click the line in blue and underlined entitled: Configure Runtime Environments
  5. on the Server Runtime Environments window,
  6. ..select Apache, expand it(click on the arrow to the left), select TOMCAT v7.0, and click EDIT.
  7. you will see a window called EDIT SERVER RUNTIME ENVIRONMENT: TOMCAT SERVER
  8. On this screen there is a pulldown labeled JREs.
  9. You should find your JRE listed like JRE1.6.0.33. If not use the Installed JRE button.
  10. Select the desired JRE. Click the FINISH button.
  11. Gracefully exit, in the Server: Server Runtime Environments window, click OK
  12. in the New Server: Define a new Server window, hit NEXT
  13. in the New Server: Add and Remove Window, select apps and install them on the server.
  14. in the New Server: Add and Remove Window, click Finish

That's all. Interesting, only steps 7-10 seem to matter, and they will change the JRE used on all servers you have previously defined to use TOMCAT v7.0. The rest of the steps are just because I can't find any other way to get to the screen except by defining a new server. Does anyone else know an easier way?

Releasing memory in Python

First, you may want to install glances:

sudo apt-get install python-pip build-essential python-dev lm-sensors 
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances

Then run it in the terminal!

glances

In your Python code, add at the begin of the file, the following:

import os
import gc # Garbage Collector

After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:

del myBigVar
gc.collect()

In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!

Good luck!

P.S. I assume you are working on a Debian or Ubuntu system

decimal vs double! - Which one should I use and when?

System.Single / float - 7 digits
System.Double / double - 15-16 digits
System.Decimal / decimal - 28-29 significant digits

The way I've been stung by using the wrong type (a good few years ago) is with large amounts:

  • ÂŁ520,532.52 - 8 digits
  • ÂŁ1,323,523.12 - 9 digits

You run out at 1 million for a float.

A 15 digit monetary value:

  • ÂŁ1,234,567,890,123.45

9 trillion with a double. But with division and comparisons it's more complicated (I'm definitely no expert in floating point and irrational numbers - see Marc's point). Mixing decimals and doubles causes issues:

A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.

When should I use double instead of decimal? has some similar and more in depth answers.

Using double instead of decimal for monetary applications is a micro-optimization - that's the simplest way I look at it.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.

The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)

Using this regex:

^(?!.*function).*(\&\$)

it is possible to search project-wide for the occurrence of &$ only in lines that are not a function definition.

This still turns up a lot of false positives, but it does make the job easier.

VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.

How to use the IEqualityComparer

Your GetHashCode implementation always returns the same value. Distinct relies on a good hash function to work efficiently because it internally builds a hash table.

When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1

In your code, the solution is to forward GetHashCode to Class_reglement.Numf.GetHashCode and implement it appropriately there.

Apart from that, your Equals method is full of unnecessary code. It could be rewritten as follows (same semantics, ÂĽ of the code, more readable):

public bool Equals(Class_reglement x, Class_reglement y)
{
    return x.Numf == y.Numf;
}

Lastly, the ToList call is unnecessary and time-consuming: AddRange accepts any IEnumerable so conversion to a List isn’t required. AsEnumerable is also redundant here since processing the result in AddRange will cause this anyway.


1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.

Postgres: SQL to list table foreign keys

Ollyc's answer is good as it is not Postgres-specific, however, it breaks down when the foreign key references more than one column. The following query works for arbitrary number of columns but it relies heavily on Postgres extensions:

select 
    att2.attname as "child_column", 
    cl.relname as "parent_table", 
    att.attname as "parent_column",
    conname
from
   (select 
        unnest(con1.conkey) as "parent", 
        unnest(con1.confkey) as "child", 
        con1.confrelid, 
        con1.conrelid,
        con1.conname
    from 
        pg_class cl
        join pg_namespace ns on cl.relnamespace = ns.oid
        join pg_constraint con1 on con1.conrelid = cl.oid
    where
        cl.relname = 'child_table'
        and ns.nspname = 'child_schema'
        and con1.contype = 'f'
   ) con
   join pg_attribute att on
       att.attrelid = con.confrelid and att.attnum = con.child
   join pg_class cl on
       cl.oid = con.confrelid
   join pg_attribute att2 on
       att2.attrelid = con.conrelid and att2.attnum = con.parent

Can we write our own iterator in Java?

The best reusable option is to implement the interface Iterable and override the method iterator().

Here's an example of a an ArrayList like class implementing the interface, in which you override the method Iterator().

import java.util.Iterator;

public class SOList<Type> implements Iterable<Type> {

    private Type[] arrayList;
    private int currentSize;

    public SOList(Type[] newArray) {
        this.arrayList = newArray;
        this.currentSize = arrayList.length;
    }

    @Override
    public Iterator<Type> iterator() {
        Iterator<Type> it = new Iterator<Type>() {

            private int currentIndex = 0;

            @Override
            public boolean hasNext() {
                return currentIndex < currentSize && arrayList[currentIndex] != null;
            }

            @Override
            public Type next() {
                return arrayList[currentIndex++];
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }
}

This class implements the Iterable interface using Generics. Considering you have elements to the array, you will be able to get an instance of an Iterator, which is the needed instance used by the "foreach" loop, for instance.

You can just create an anonymous instance of the iterator without creating extending Iterator and take advantage of the value of currentSize to verify up to where you can navigate over the array (let's say you created an array with capacity of 10, but you have only 2 elements at 0 and 1). The instance will have its owner counter of where it is and all you need to do is to play with hasNext(), which verifies if the current value is not null, and the next(), which will return the instance of your currentIndex. Below is an example of using this API...

public static void main(String[] args) {
    // create an array of type Integer
    Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};

    // create your list and hold the values.
    SOList<Integer> stackOverflowList = new SOList<Integer>(numbers);

    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(Integer num : stackOverflowList) {
        System.out.print(num);
    }

    // creating an array of Strings
    String[] languages = new String[]{"C", "C++", "Java", "Python", "Scala"};

    // create your list and hold the values using the same list implementation.
    SOList<String> languagesList = new SOList<String>(languages);

    System.out.println("");
    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(String lang : languagesList) {
        System.out.println(lang);
    }
}
// will print "12345
//C
//C++
//Java
//Python
//Scala

If you want, you can iterate over it as well using the Iterator instance:

// navigating the iterator
while (allNumbers.hasNext()) {
    Integer value = allNumbers.next();
    if (allNumbers.hasNext()) {
        System.out.print(value + ", ");
    } else {
        System.out.print(value);
    }
} 
// will print 1, 2, 3, 4, 5

The foreach documentation is located at http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html. You can take a look at a more complete implementation at my personal practice google code.

Now, to get the effects of what you need I think you need to plug a concept of a filter in the Iterator... Since the iterator depends on the next values, it would be hard to return true on hasNext(), and then filter the next() implementation with a value that does not start with a char "a" for instance. I think you need to play around with a secondary Interator based on a filtered list with the values with the given filter.

Add new attribute (element) to JSON object using JavaScript

You can also use Object.assign from ECMAScript 2015. It also allows you to add nested attributes at once. E.g.:

const myObject = {};

Object.assign(myObject, {
    firstNewAttribute: {
        nestedAttribute: 'woohoo!'
    }
});

Ps: This will not override the existing object with the assigned attributes. Instead they'll be added. However if you assign a value to an existing attribute then it would be overridden.

MultipartException: Current request is not a multipart request

It looks like the problem is request to server is not a multi-part request. Basically you need to modify your client-side form. For example:

<form action="..." method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
</form>

Hope this helps.

Assign pandas dataframe column dtypes

facing similar problem to you. In my case I have 1000's of files from cisco logs that I need to parse manually.

In order to be flexible with fields and types I have successfully tested using StringIO + read_cvs which indeed does accept a dict for the dtype specification.

I usually get each of the files ( 5k-20k lines) into a buffer and create the dtype dictionaries dynamically.

Eventually I concatenate ( with categorical... thanks to 0.19) these dataframes into a large data frame that I dump into hdf5.

Something along these lines

import pandas as pd
import io 

output = io.StringIO()
output.write('A,1,20,31\n')
output.write('B,2,21,32\n')
output.write('C,3,22,33\n')
output.write('D,4,23,34\n')

output.seek(0)


df=pd.read_csv(output, header=None,
        names=["A","B","C","D"],
        dtype={"A":"category","B":"float32","C":"int32","D":"float64"},
        sep=","
       )

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
A    5 non-null category
B    5 non-null float32
C    5 non-null int32
D    5 non-null float64
dtypes: category(1), float32(1), float64(1), int32(1)
memory usage: 205.0 bytes
None

Not very pythonic.... but does the job

Hope it helps.

JC

How to find tag with particular text with Beautiful Soup?

A solution for finding a anchor tag if having a particular keyword would be the following:

from bs4 import BeautifulSoup
from urllib.request import urlopen,Request
from urllib.parse import urljoin,urlparse

rawLinks=soup.findAll('a',href=True)
for link in rawLinks:
    innercontent=link.text
    if keyword.lower() in innercontent.lower():
        print(link)

Oracle SELECT TOP 10 records

You get an apparently random set because ROWNUM is applied before the ORDER BY. So your query takes the first ten rows and sorts them.0 To select the top ten salaries you should use an analytic function in a subquery, then filter that:

 select * from 
     (select empno,
             ename,
             sal,
             row_number() over(order by sal desc nulls last) rnm
    from emp) 
 where rnm<=10

How to get < span > value?

var test = document.getElementById( 'test' );

// To get the text only, you can use "textContent"
console.log( test.textContent ); // "1 2 3 4"

textContent is the standard way. innerText is the property to use for legacy IE. If you want something as cross browser as possible, recursively use nodeValue.

mysql update column with value from another table

If you have common field in both table then it's so easy !....

Table-1 = table where you want to update. Table-2 = table where you from take data.

  1. make query in Table-1 and find common field value.
  2. make a loop and find all data from Table-2 according to table 1 value.
  3. again make update query in table 1.

$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");

$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}



foreach($resultArray as $rec) {

    $a = $rec['primary key field'];

    $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");

    $cuttable = mysql_fetch_assoc($cuttable_qry);



    echo $x= $cuttable['Table-2 field']; echo " ! ";
    echo $y= $cuttable['Table-2 field'];echo " ! ";
    echo $z= $cuttable['Table-2 field'];echo " ! ";


    $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");

    if ($k) {
        echo "done";
    } else {
        echo mysql_error();
    }


}

How to force uninstallation of windows service

Also make sure that there are no instances of the executable still active (perhaps one that might have been running, for whatever reason, independently of the service).

I was opening and closing MMC and looking for the PIDs to kill - but when looking in process explorer there were a couple of extant processes running from a forgotten scheduled batch. Killed them. Job done.

How can I check if my Element ID has focus?

Use document.activeElement

Should work.

P.S getElementById("myID") not getElementById("#myID")

What is the equivalent of 'describe table' in SQL Server?

The query below will provide similar output as the info() function in python, Pandas library.

USE [Database_Name]

IF OBJECT_ID('tempdo.dob.#primary_key', 'U') IS NOT NULL DROP TABLE #primary_key

SELECT 
CONS_T.TABLE_CATALOG,
CONS_T.TABLE_SCHEMA,
CONS_T.TABLE_NAME,
CONS_C.COLUMN_NAME,
CONS_T.CONSTRAINT_TYPE,
CONS_T.CONSTRAINT_NAME
INTO  #primary_key
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS CONS_T 
JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CONS_C ON CONS_C.CONSTRAINT_NAME= CONS_T.CONSTRAINT_NAME


SELECT
SMA.name AS [Schema Name],
ST.name AS [Table Name],
SC.column_id AS [Column Order],
SC.name AS [Column Name],
PKT.CONSTRAINT_TYPE, 
PKT.CONSTRAINT_NAME, 
SC.system_type_id,
STP.name AS [Data Type],
SC.max_length,
SC.precision, 
SC.scale, 
SC.is_nullable, 
SC.is_masked
FROM sys.tables  AS ST
JOIN sys.schemas AS SMA ON SMA.schema_id = ST.schema_id
JOIN sys.columns AS SC ON SC.object_id = ST.object_id 
JOIN sys.types AS STP ON STP.system_type_id = SC.system_type_id
LEFT JOIN #primary_key AS PKT ON PKT.TABLE_SCHEMA = SMA.name
                                 AND PKT.TABLE_NAME = ST.name
                                 AND PKT.COLUMN_NAME = SC.name
ORDER BY ST.name ASC, SMA.name ASC

Center fixed div with dynamic width (CSS)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

Android Webview gives net::ERR_CACHE_MISS message

To Solve this Error in Webview Android, First Check the Permissions in Manifest.xml, if not define there,then define as like this. <uses-permission android:name="android.permission.INTERNET"/>

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

What is a tracking branch?

The Pro Git book mentions:

Tracking branches are local branches that have a direct relationship to a remote branch

Not exactly. The SO question "Having a hard time understanding git-fetch" includes:

There's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo.

But actually, once you establish an upstream branch relationship between:

  • a local branch like master
  • and a remote tracking branch like origin/master

Then you can consider master as a local tracking branch: It tracks the remote tracking branch origin/master which, in turn, tracks the master branch of the upstream repo origin.

alt text

Creating Roles in Asp.net Identity MVC 5

In ASP.NET 5 rc1-final, I did following:

Created ApplicationRoleManager (in similar manner as there is ApplicationUser created by template)

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(
        IRoleStore<IdentityRole> store,
        IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
        ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors,
        ILogger<RoleManager<IdentityRole>> logger,
        IHttpContextAccessor contextAccessor)
        : base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
    {
    }
}

To ConfigureServices in Startup.cs, I added it as RoleManager

services.
    .AddIdentity<ApplicationUser, IdentityRole>()
    .AddRoleManager<ApplicationRoleManager>();

For creating new Roles, call from Configure following:

public static class RoleHelper
{
    private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
    {
        if (!await roleManager.RoleExistsAsync(roleName))
        {
            await roleManager.CreateAsync(new IdentityRole(roleName));
        }
    }
    public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
    {
        // add all roles, that should be in database, here
        await EnsureRoleCreated(roleManager, "Developer");
    }
}

public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
     ...
     await roleManager.EnsureRolesCreated();
     ...
}

Now, the rules can be assigned to user

await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");

Or used in Authorize attribute

[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}

How to reload a page after the OK click on the Alert Page

As the alert method in JavaScript does not return a Boolean or yield the current thread, you must use a different method.

My number one recommendation requires a little CSS experience. You should instead create a div element that is fixed positionally.

Otherwise you could use the confirm() method.

confirm("Successful Message");
window.location.reload();

However, this will add a cancel button. Because the confirm method is not within an if statement though, the cancel button will still refresh the page like you want it.

Calling C/C++ from Python?

Cython is definitely the way to go, unless you anticipate writing Java wrappers, in which case SWIG may be preferable.

I recommend using the runcython command line utility, it makes the process of using Cython extremely easy. If you need to pass structured data to C++, take a look at Google's protobuf library, it's very convenient.

Here is a minimal examples I made that uses both tools:

https://github.com/nicodjimenez/python2cpp

Hope it can be a useful starting point.

How can I send JSON response in symfony2 controller

If your data is already serialized:

a) send a JSON response

public function someAction()
{
    $response = new Response();
    $response->setContent(file_get_contents('path/to/file'));
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

b) send a JSONP response (with callback)

public function someAction()
{
    $response = new Response();
    $response->setContent('/**/FUNCTION_CALLBACK_NAME(' . file_get_contents('path/to/file') . ');');
    $response->headers->set('Content-Type', 'text/javascript');
    return $response;
}

If your data needs be serialized:

c) send a JSON response

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    return $response;
}

d) send a JSONP response (with callback)

public function someAction()
{
    $response = new JsonResponse();
    $response->setData([some array]);
    $response->setCallback('FUNCTION_CALLBACK_NAME');
    return $response;
}

e) use groups in Symfony 3.x.x

Create groups inside your Entities

<?php

namespace Mindlahus;

use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Some Super Class Name
 *
 * @ORM    able("table_name")
 * @ORM\Entity(repositoryClass="SomeSuperClassNameRepository")
 * @UniqueEntity(
 *  fields={"foo", "boo"},
 *  ignoreNull=false
 * )
 */
class SomeSuperClassName
{
    /**
     * @Groups({"group1", "group2"})
     */
    public $foo;
    /**
     * @Groups({"group1"})
     */
    public $date;

    /**
     * @Groups({"group3"})
     */
    public function getBar() // is* methods are also supported
    {
        return $this->bar;
    }

    // ...
}

Normalize your Doctrine Object inside the logic of your application

<?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
// For annotations
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

...

$repository = $this->getDoctrine()->getRepository('Mindlahus:SomeSuperClassName');
$SomeSuperObject = $repository->findOneById($id);

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer($classMetadataFactory);
$callback = function ($dateTime) {
    return $dateTime instanceof \DateTime
        ? $dateTime->format('m-d-Y')
        : '';
};
$normalizer->setCallbacks(array('date' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$data = $serializer->normalize($SomeSuperObject, null, array('groups' => array('group1')));

$response = new Response();
$response->setContent($serializer->serialize($data, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;

How to declare a constant map in Golang?

Your syntax is incorrect. To make a literal map (as a pseudo-constant), you can do:

var romanNumeralDict = map[int]string{
  1000: "M",
  900 : "CM",
  500 : "D",
  400 : "CD",
  100 : "C",
  90  : "XC",
  50  : "L",
  40  : "XL",
  10  : "X",
  9   : "IX",
  5   : "V",
  4   : "IV",
  1   : "I",
}

Inside a func you can declare it like:

romanNumeralDict := map[int]string{
...

And in Go there is no such thing as a constant map. More information can be found here.

Try it out on the Go playground.

Node.js: Python not found exception due to node-sass and node-gyp

Node-sass tries to download the binary for you platform when installing. Node 5 is supported by 3.8 https://github.com/sass/node-sass/releases/tag/v3.8.0 If your Jenkins can't download the prebuilt binary, then you need to follow the platform requirements on Node-gyp README (Python2, VS or MSBuild, ...) If possible I'd suggest updating your Node to at least 6 since 5 isn't supported by Node anymore. If you want to upgrade to 8, you'll need to update node-sass to 4.5.3

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Great solution, thank you! I took the AndyDBell's question and Cuong Le's answer to build an example with two diferent interface's implementation:

public interface ISample
{
    int SampleId { get; set; }
}

public class Sample1 : ISample
{
    public int SampleId { get; set; }
    public Sample1() { }
}


public class Sample2 : ISample
{
    public int SampleId { get; set; }
    public String SampleName { get; set; }
    public Sample2() { }
}

public class SampleGroup
{
    public int GroupId { get; set; }
    public IEnumerable<ISample> Samples { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        //Sample1 instance
        var sz = "{\"GroupId\":1,\"Samples\":[{\"SampleId\":1},{\"SampleId\":2}]}";
        var j = JsonConvert.DeserializeObject<SampleGroup>(sz, new SampleConverter<Sample1>());
        foreach (var item in j.Samples)
        {
            Console.WriteLine("id:{0}", item.SampleId);
        }
        //Sample2 instance
        var sz2 = "{\"GroupId\":1,\"Samples\":[{\"SampleId\":1, \"SampleName\":\"Test1\"},{\"SampleId\":2, \"SampleName\":\"Test2\"}]}";
        var j2 = JsonConvert.DeserializeObject<SampleGroup>(sz2, new SampleConverter<Sample2>());
        //Print to show that the unboxing to Sample2 preserved the SampleName's values
        foreach (var item in j2.Samples)
        {
            Console.WriteLine("id:{0} name:{1}", item.SampleId, (item as Sample2).SampleName);
        }
        Console.ReadKey();
    }
}

And a generic version to the SampleConverter:

public class SampleConverter<T> : CustomCreationConverter<ISample> where T: new ()
{
    public override ISample Create(Type objectType)
    {
        return ((ISample)new T());
    }
}

How to save/restore serializable object to/from file?

1. Restore Object From File

From Here you can deserialize an object from file in two way.

Solution-1: Read file into a string and deserialize JSON to a type

string json = File.ReadAllText(@"c:\myObj.json");
MyObject myObj = JsonConvert.DeserializeObject<MyObject>(json);

Solution-2: Deserialize JSON directly from a file

using (StreamReader file = File.OpenText(@"c:\myObj.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    MyObject myObj2 = (MyObject)serializer.Deserialize(file, typeof(MyObject));
}

2. Save Object To File

from here you can serialize an object to file in two way.

Solution-1: Serialize JSON to a string and then write string to a file

string json = JsonConvert.SerializeObject(myObj);
File.WriteAllText(@"c:\myObj.json", json);

Solution-2: Serialize JSON directly to a file

using (StreamWriter file = File.CreateText(@"c:\myObj.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(file, myObj);
}

3. Extra

You can download Newtonsoft.Json from NuGet by following command

Install-Package Newtonsoft.Json

jQuery Ajax requests are getting cancelled without being sent

Two possibilities are there when AJAX request gets dropped (if not Cross-Origin request):

  1. You are not preventing the element's default behavior for the event.
  2. You set timeout of AJAX too low, or network/application backend server is slow.

Solution for 1): Add return false; or e.preventDefault(); in the event handler.

Solution for 2): Add timeout option while forming the AJAX request. Example below.

$.ajax({
    type: 'POST',
    url: url,
    timeout: 86400,
    data: data,
    success: success,
    dataType: dataType
});

For Cross-origin requests, check Cross-Origin Resource Sharing (CORS) HTTP headers.

How to vertically center a <span> inside a div?

As in a similar question, use display: inline-block with a placeholder element to vertically center the span inside of a block element:

_x000D_
_x000D_
html, body, #container, #placeholder { height: 100%; }_x000D_
_x000D_
#content, #placeholder { display:inline-block; vertical-align: middle; }
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="container">_x000D_
      <span id="content">_x000D_
        Content_x000D_
      </span>_x000D_
      <span id="placeholder"></span>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Vertical alignment is only applied to inline elements or table cells, so use it along with display:inline-block or display:table-cell with a display:table parent when vertically centering block elements.

References:

CSS Horizontal and Vertical Centering

Check if a key exists inside a json object

function to check undefined and null objects

function elementCheck(objarray, callback) {
        var list_undefined = "";
        async.forEachOf(objarray, function (item, key, next_key) {
            console.log("item----->", item);
            console.log("key----->", key);
            if (item == undefined || item == '') {
                list_undefined = list_undefined + "" + key + "!!  ";
                next_key(null);
            } else {
                next_key(null);
            }
        }, function (next_key) {
            callback(list_undefined);
        })
    }

here is an easy way to check whether object sent is contain undefined or null

var objarray={
"passenger_id":"59b64a2ad328b62e41f9050d",
"started_ride":"1",
"bus_id":"59b8f920e6f7b87b855393ca",
"route_id":"59b1333c36a6c342e132f5d5",
"start_location":"",
"stop_location":""
}
elementCheck(objarray,function(list){
console.log("list");
)

Get the current cell in Excel VB

This may not help answer your question directly but is something I have found useful when trying to work with dynamic ranges that may help you out.

Suppose in your worksheet you have the numbers 100 to 108 in cells A1:C3:

          A    B    C  
1        100  101  102
2        103  104  105
3        106  107  108

Then to select all the cells you can use the CurrentRegion property:

Sub SelectRange()
Dim dynamicRange As Range

Set dynamicRange = Range("A1").CurrentRegion

End Sub

The advantage of this is that if you add new rows or columns to your block of numbers (e.g. 109, 110, 111) then the CurrentRegion will always reference the enlarged range (in this case A1:C4).

I have used CurrentRegion quite a bit in my VBA code and find it is most useful when working with dynmacially sized ranges. Also it avoids having to hard code ranges in your code.

As a final note, in my code you will see that I used A1 as the reference cell for CurrentRegion. It will also work no matter which cell you reference (try: replacing A1 with B2 for example). The reason is that CurrentRegion will select all contiguous cells based on the reference cell.

TypeError: $(...).modal is not a function with bootstrap Modal

This error is actually the result of you not including bootstrap's javascript before calling the modal function. Modal is defined in bootstrap.js not jQuery. It's also important to note that bootstrap actually needs jQuery to define the modal function, so it's vital that you include jQuery before including bootstrap's javascript. To avoid the error just be sure to include jQuery then bootstrap's javascript before you call the modal function. I usually do the following in my header tag:

<header>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="/path/to/bootstrap/js/bootstrap.min.js"></script>
</header>

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

You can use:

  1. size_t type, to remove warning messages
  2. iterators + distance (like are first hint)
  3. only iterators
  4. function object

For example:

// simple class who output his value
class ConsoleOutput
{
public:
  ConsoleOutput(int value):m_value(value) { }
  int Value() const { return m_value; }
private:
  int m_value;
};

// functional object
class Predicat
{
public:
  void operator()(ConsoleOutput const& item)
  {
    std::cout << item.Value() << std::endl;
  }
};

void main()
{
  // fill list
  std::vector<ConsoleOutput> list;
  list.push_back(ConsoleOutput(1));
  list.push_back(ConsoleOutput(8));

  // 1) using size_t
  for (size_t i = 0; i < list.size(); ++i)
  {
    std::cout << list.at(i).Value() << std::endl;
  }

  // 2) iterators + distance, for std::distance only non const iterators
  std::vector<ConsoleOutput>::iterator itDistance = list.begin(), endDistance = list.end();
  for ( ; itDistance != endDistance; ++itDistance)
  {
    // int or size_t
    int const position = static_cast<int>(std::distance(list.begin(), itDistance));
    std::cout << list.at(position).Value() << std::endl;
  }

  // 3) iterators
  std::vector<ConsoleOutput>::const_iterator it = list.begin(), end = list.end();
  for ( ; it != end; ++it)
  {
    std::cout << (*it).Value() << std::endl;
  }
  // 4) functional objects
  std::for_each(list.begin(), list.end(), Predicat());
}

How are booleans formatted in Strings in Python?

To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

Thank you all! i managed to do what i wanted :D http://jsfiddle.net/Tfc9j/42/ here take a look

i wanted to have the opacity of an outer div to be different from the opacity of the internal div and that change with a click somwewhere ;) Thanks!

   $('#ena').on('click', function () {
        $('head').append("<style>#ena:before { opacity:0.3; }</style>");
    });

$('#duop').on('click', function (e) {

        $('head').append("<style>#ena:before { opacity:0.8; }</style>");

     e.stopPropagation(); 
    });

#ena{
    width:300px;
    height:300px;
    border:1px black solid;
    position:relative;
}
#duo{
    opacity:1;
    position:absolute;
    top:50px;
  width:300px;
    height:100px;
      background-color:white;
}
#ena:before {
    content: attr(data-before);
    color: white;
    cursor: pointer;
    position: absolute;
    background-color:red;
    opacity:0.9;
    width:100%;
    height:100%;
}


<div id="ena">
    <div id="duo">
        <p>ena p</p>
        <p id="duop">duoyyyyyyyyyyyyyy p</p>

    </div>   


</div>

Sleeping in a batch file

You can use ping:

ping 127.0.0.1 -n 11 -w 1000 >nul: 2>nul:

It will wait 10 seconds.

The reason you have to use 11 is because the first ping goes out immediately, not after one second. The number should always be one more than the number of seconds you want to wait.

Keep in mind that the purpose of the -w is not to wait one second. It's to ensure that you wait no more than one second in the event that there are network problems. ping on its own will send one ICMP packet per second. It's probably not required for localhost, but old habits die hard.

Delete element in a slice

... is syntax for variadic arguments.

I think it is implemented by the complier using slice ([]Type), just like the function append :

func append(slice []Type, elems ...Type) []Type

when you use "elems" in "append", actually it is a slice([]type). So "a = append(a[:0], a[1:]...)" means "a = append(a[0:0], a[1:])"

a[0:0] is a slice which has nothing

a[1:] is "Hello2 Hello3"

This is how it works

How to SELECT WHERE NOT EXIST using LINQ?

How about..

var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)

Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest

Error "library not found for" after putting application in AdMob

Sometimes you just remove the reference of the library and add reference again.

Apart from adding the Google Mobile Ads SDK and other libraries again from scratch, I would recommend you checking the Library Search Paths. There are instances when you copy or duplicate a target, Xcode decides that it needs to escape any double quotes " with a '\'. Make sure you remove all the \’s - it should look like this -

enter image description here

I was able to duplicate the error, by doing prefixing my path with multiple '\'.

How do I get TimeSpan in minutes given two Dates?

See TimeSpan.TotalMinutes:

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

jQuery $("#radioButton").change(...) not firing during de-selection

Let's say those radio buttons are inside a div that has the id radioButtons and that the radio buttons have the same name (for example commonName) then:

$('#radioButtons').on('change', 'input[name=commonName]:radio', function (e) {
    console.log('You have changed the selected radio button!');
});

Data access object (DAO) in Java

Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern.

Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).

Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.

Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

Sample code here..

Keep values selected after form submission

This works for me!

<label for="reason">Reason:</label>
<select name="reason" size="1" id="name" >
    <option value="NG" selected="SELECTED"><?php if (!(strcmp("NG", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>Selection a reason below</option>
    <option value="General"<?php if (!(strcmp("General", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>General Question</option>
    <option value="Account"<?php if (!(strcmp("Account", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Account Question</option>
    <option value="Other"<?php if (!(strcmp("Other", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Other</option>

</select>

Facebook Graph API : get larger pictures in one request

You can also try getting the image if you want it based on the height or width

https://graph.facebook.com/user_id/picture?height=

OR

https://graph.facebook.com/user_id/picture?width=

The values are by default in pixels you just need to provide the int value

creating json object with variables

var formValues = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    phone: $('#phoneNumber').val(),
    address: $('#address').val()
};

Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

How can I render Partial views in asp.net mvc 3?

<%= Html.Partial("PartialName", Model) %>

An existing connection was forcibly closed by the remote host

I got the same issue while using .NET Framework 4.5. However, when I update the .NET version to 4.7.2 connection issue was resolved. Maybe this is due to SecurityProtocol support issue.

How to Return partial view of another controller by controller?

The control searches for a view in the following order:

  • First in shared folder
  • Then in the folder matching the current controller (in your case it's Views/DEF)

As you do not have xxx.cshtml in those locations, it returns a "view not found" error.

Solution: You can use the complete path of your view:

Like

 PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

Apply function to pandas groupby

Try:

g = pd.DataFrame(['A','B','A','C','D','D','E'])

# Group by the contents of column 0 
gg = g.groupby(0)  

# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())

# Add a new column that is the count / total number of elements    
histo[1] = histo.astype(np.float)/len(g) 

print histo

Output:

   0         1
0             
A  2  0.285714
B  1  0.142857
C  1  0.142857
D  2  0.285714
E  1  0.142857

How to amend a commit without changing commit message (reusing the previous one)?

just to add some clarity, you need to stage changes with git add, then amend last commit:

git add /path/to/modified/files
git commit --amend --no-edit

This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.

HTML <select> selected option background-color CSS style

We Can override the blue color in to our custom color It works for Internet Explorer, Firefox and Chrome:

By using this below following CSS:

option: checked, option: hover {
    Color: #ffffff;
    background: #614767 repeat url("data:image/gif;base64,R0lGODlh8ACgAPAAAGFGZQAAACH5BAAAAAAALAAAAADwAKAAAAL+hI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8PGCg4SFhoeIiYqLjI2Oj4CBkpOUlZaXmJmam5ydnp+QkaKjpKWmp6ipqqusra6voKGys7S1tre4ubq7vL2+v7CxwsPExcbHyMnKy8zNzs/AwdLT1NXW19jZ2tvc3d7f0NHi4+Tl5ufo6err7O3u7+Dh8vP09fb3+Pn6+/z9/v/w8woMCBBAsaPIgwocKFDBs6fAgxosSJFCtavIhRVgEAOw");
}

npm install Error: rollbackFailedOptional

Make sure you can access the corporate repository you configured in npm is available.Check you VPN connection.

Else reset it back to default repository like below.

npm config set registry http://registry.npmjs.org/

Good Luck!!

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

If you declare your callback as mentioned by @lex82 like

callback = "callback(item.id, arg2)"

You can call the callback method in the directive scope with object map and it would do the binding correctly. Like

scope.callback({arg2:"some value"});

without requiring for $parse. See my fiddle(console log) http://jsfiddle.net/k7czc/2/

Update: There is a small example of this in the documentation:

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

C - casting int to char and append char to char

int i = 100;
char c = (char)i;

There is no way to append one char to another. But you can create an array of chars and use it.

What is the difference between logical data model and conceptual data model?

These terms are unfortunately overloaded with several possible definitions. According to the ANSI-SPARC "three schema" model for instance, the Conceptual Schema or Conceptual Model consists of the set of objects in a database (tables, views, etc) in contrast to the External Schema which are the objects that users see.

In the data management professions and especially among data modellers / architects, the term Conceptual Model is frequently used to mean a semantic model whereas the term Logical Model is used to mean a preliminary or virtual database design. This is probably the usage you are most likely to come across in the workplace.

In academic usage and when describing DBMS architectures however, the Logical level means the database objects (tables, views, tables, keys, constraints, etc), as distinct from the Physical level (files, indexes, storage). To confuse things further, in the workplace the term Physical model is often used to mean the design as implemented or planned for implementation in an actual database. That may include both "physical" and "logical" level constructs (both tables and indexes for example).

When you come across any of these terms you really need to seek clarification on what is being described unless the context makes it obvious.

For a discussion of these differences, check out Data Modelling Essentials by Simsion and Witt for example.

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

JavaScript closure inside loops – simple practical example

var funcs = [];
for (var i = 0; i < 3; i++) {      // let's create 3 functions
  funcs[i] = function(param) {          // and store them in funcs
    console.log("My value: " + param); // each should log its value.
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j](j);                      // and now let's run each one to see with j
}

MySQL: #126 - Incorrect key file for table

repair table myschema.mytable;

How to encrypt/decrypt data in php?

Foreword

Starting with your table definition:

- UserID
- Fname
- Lname
- Email
- Password
- IV

Here are the changes:

  1. The fields Fname, Lname and Email will be encrypted using a symmetric cipher, provided by OpenSSL,
  2. The IV field will store the initialisation vector used for encryption. The storage requirements depend on the cipher and mode used; more about this later.
  3. The Password field will be hashed using a one-way password hash,

Encryption

Cipher and mode

Choosing the best encryption cipher and mode is beyond the scope of this answer, but the final choice affects the size of both the encryption key and initialisation vector; for this post we will be using AES-256-CBC which has a fixed block size of 16 bytes and a key size of either 16, 24 or 32 bytes.

Encryption key

A good encryption key is a binary blob that's generated from a reliable random number generator. The following example would be recommended (>= 5.3):

$key_size = 32; // 256 bits
$encryption_key = openssl_random_pseudo_bytes($key_size, $strong);
// $strong will be true if the key is crypto safe

This can be done once or multiple times (if you wish to create a chain of encryption keys). Keep these as private as possible.

IV

The initialisation vector adds randomness to the encryption and required for CBC mode. These values should be ideally be used only once (technically once per encryption key), so an update to any part of a row should regenerate it.

A function is provided to help you generate the IV:

$iv_size = 16; // 128 bits
$iv = openssl_random_pseudo_bytes($iv_size, $strong);

Example

Let's encrypt the name field, using the earlier $encryption_key and $iv; to do this, we have to pad our data to the block size:

function pkcs7_pad($data, $size)
{
    $length = $size - strlen($data) % $size;
    return $data . str_repeat(chr($length), $length);
}

$name = 'Jack';
$enc_name = openssl_encrypt(
    pkcs7_pad($name, 16), // padded data
    'AES-256-CBC',        // cipher and mode
    $encryption_key,      // secret key
    0,                    // options (not used)
    $iv                   // initialisation vector
);

Storage requirements

The encrypted output, like the IV, is binary; storing these values in a database can be accomplished by using designated column types such as BINARY or VARBINARY.

The output value, like the IV, is binary; to store those values in MySQL, consider using BINARY or VARBINARY columns. If this is not an option, you can also convert the binary data into a textual representation using base64_encode() or bin2hex(), doing so requires between 33% to 100% more storage space.

Decryption

Decryption of the stored values is similar:

function pkcs7_unpad($data)
{
    return substr($data, 0, -ord($data[strlen($data) - 1]));
}

$row = $result->fetch(PDO::FETCH_ASSOC); // read from database result
// $enc_name = base64_decode($row['Name']);
// $enc_name = hex2bin($row['Name']);
$enc_name = $row['Name'];
// $iv = base64_decode($row['IV']);
// $iv = hex2bin($row['IV']);
$iv = $row['IV'];

$name = pkcs7_unpad(openssl_decrypt(
    $enc_name,
    'AES-256-CBC',
    $encryption_key,
    0,
    $iv
));

Authenticated encryption

You can further improve the integrity of the generated cipher text by appending a signature that's generated from a secret key (different from the encryption key) and the cipher text. Before the cipher text is decrypted, the signature is first verified (preferably with a constant-time comparison method).

Example

// generate once, keep safe
$auth_key = openssl_random_pseudo_bytes(32, $strong);

// authentication
$auth = hash_hmac('sha256', $enc_name, $auth_key, true);
$auth_enc_name = $auth . $enc_name;

// verification
$auth = substr($auth_enc_name, 0, 32);
$enc_name = substr($auth_enc_name, 32);
$actual_auth = hash_hmac('sha256', $enc_name, $auth_key, true);

if (hash_equals($auth, $actual_auth)) {
    // perform decryption
}

See also: hash_equals()

Hashing

Storing a reversible password in your database must be avoided as much as possible; you only wish to verify the password rather than knowing its contents. If a user loses their password, it's better to allow them to reset it rather than sending them their original one (make sure that password reset can only be done for a limited time).

Applying a hash function is a one-way operation; afterwards it can be safely used for verification without revealing the original data; for passwords, a brute force method is a feasible approach to uncover it due to its relatively short length and poor password choices of many people.

Hashing algorithms such as MD5 or SHA1 were made to verify file contents against a known hash value. They're greatly optimized to make this verification as fast as possible while still being accurate. Given their relatively limited output space it was easy to build a database with known passwords and their respective hash outputs, the rainbow tables.

Adding a salt to the password before hashing it would render a rainbow table useless, but recent hardware advancements made brute force lookups a viable approach. That's why you need a hashing algorithm that's deliberately slow and simply impossible to optimize. It should also be able to increase the load for faster hardware without affecting the ability to verify existing password hashes to make it future proof.

Currently there are two popular choices available:

  1. PBKDF2 (Password Based Key Derivation Function v2)
  2. bcrypt (aka Blowfish)

This answer will use an example with bcrypt.

Generation

A password hash can be generated like this:

$password = 'my password';
$random = openssl_random_pseudo_bytes(18);
$salt = sprintf('$2y$%02d$%s',
    13, // 2^n cost factor
    substr(strtr(base64_encode($random), '+', '.'), 0, 22)
);

$hash = crypt($password, $salt);

The salt is generated with openssl_random_pseudo_bytes() to form a random blob of data which is then run through base64_encode() and strtr() to match the required alphabet of [A-Za-z0-9/.].

The crypt() function performs the hashing based on the algorithm ($2y$ for Blowfish), the cost factor (a factor of 13 takes roughly 0.40s on a 3GHz machine) and the salt of 22 characters.

Validation

Once you have fetched the row containing the user information, you validate the password in this manner:

$given_password = $_POST['password']; // the submitted password
$db_hash = $row['Password']; // field with the password hash

$given_hash = crypt($given_password, $db_hash);

if (isEqual($given_hash, $db_hash)) {
    // user password verified
}

// constant time string compare
function isEqual($str1, $str2)
{
    $n1 = strlen($str1);
    if (strlen($str2) != $n1) {
        return false;
    }
    for ($i = 0, $diff = 0; $i != $n1; ++$i) {
        $diff |= ord($str1[$i]) ^ ord($str2[$i]);
    }
    return !$diff;
}

To verify a password, you call crypt() again but you pass the previously calculated hash as the salt value. The return value yields the same hash if the given password matches the hash. To verify the hash, it's often recommended to use a constant-time comparison function to avoid timing attacks.

Password hashing with PHP 5.5

PHP 5.5 introduced the password hashing functions that you can use to simplify the above method of hashing:

$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 13]);

And verifying:

if (password_verify($given_password, $db_hash)) {
    // password valid
}

See also: password_hash(), password_verify()

Screen width in React Native

April 10th 2020 Answer:

The suggested answer using Dimensions is now discouraged. See: https://reactnative.dev/docs/dimensions

The recommended approach is using the useWindowDimensions hook in React; https://reactnative.dev/docs/usewindowdimensions which uses a hook based API and will also update your value when the screen value changes (on screen rotation for example):

import {useWindowDimensions} from 'react-native';

const windowWidth = useWindowDimensions().width;
const windowHeight = useWindowDimensions().height;

Note: useWindowDimensions is only available from React Native 0.61.0: https://reactnative.dev/blog/2019/09/18/version-0.61

Serializing and submitting a form with jQuery and PHP

You can add extra data with form data

use serializeArray and add the additional data:

var data = $('#myForm').serializeArray();
    data.push({name: 'tienn2t', value: 'love'});
    $.ajax({
      type: "POST",
      url: "your url.php",
      data: data,
      dataType: "json",
      success: function(data) {
          //var obj = jQuery.parseJSON(data); if the dataType is not     specified as json uncomment this
        // do what ever you want with the server response
     },
    error: function() {
        alert('error handing here');
    }
});

How do I install Keras and Theano in Anaconda Python on Windows?

The trick is that you need to create an environment/workspace for Python. This solution should work for Python 2.7 but at the time of writing keras can run on python 3.5, especially if you have the latest anaconda installed (this took me awhile to figure out so I'll outline the steps I took to install KERAS in python 3.5):

Create environment/workspace for Python 3.5

  1. C:\conda create --name neuralnets python=3.5
  2. C:\activate neuralnets

Install everything (notice the neuralnets workspace in parenthesis on each line). Accept any dependencies each of those steps wants to install:

  1. (neuralnets) C:\conda install theano
  2. (neuralnets) C:\conda install mingw libpython
  3. (neuralnets) C:\pip install tensorflow
  4. (neuralnets) C:\pip install keras

Test it out:

(neuralnets) C:\python -c "from keras import backend; print(backend._BACKEND)"

Just remember, if you want to work in the workspace you always have to do:

C:\activate neuralnets

so you can launch Jupyter for example (assuming you also have Jupyter installed in this environment/workspace) as:

C:\activate neuralnets
(neuralnets) jupyter notebook

You can read more about managing and creating conda environments/workspaces at the follwing URL: https://conda.io/docs/using/envs.html

How do I resolve `The following packages have unmet dependencies`

The command to have Ubuntu fix unmet dependencies and broken packages is

sudo apt-get install -f

from the man page:

-f, --fix-broken Fix; attempt to correct a system with broken dependencies in place. This option, when used with install/remove, can omit any packages to permit APT to deduce a likely solution. If packages are specified, these have to completely correct the problem. The option is sometimes necessary when running APT for the first time; APT itself does not allow broken package dependencies to exist on a system. It is possible that a system's dependency structure can be so corrupt as to require manual intervention (which usually means using dselect(1) or dpkg --remove to eliminate some of the offending packages)

Ubuntu will try to fix itself when you run the command. When it completes, you can test if it worked by running the command again, and you should receive output similar to:

Reading package lists... Done Building dependency tree Reading state information... Done 0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.

How to load data to hive from HDFS without removing the source file?

I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').

When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.

If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).

Matplotlib scatter plot with different text at each data point

For limited set of values matplotlib is fine. But when you have lots of values the tooltip starts to overlap over other data points. But with limited space you can't ignore the values. Hence it's better to zoom out or zoom in.

Using plotly

import plotly.express as px
df = px.data.tips()

df = px.data.gapminder().query("year==2007 and continent=='Americas'")


fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="country", log_x=True, size_max=100, color="lifeExp")
fig.update_traces(textposition='top center')
fig.update_layout(title_text='Life Expectency', title_x=0.5)
fig.show()

enter image description here

Replace Both Double and Single Quotes in Javascript String

mystring = mystring.replace(/["']/g, "");

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

git cherry-pick says "...38c74d is a merge but no -m option was given"

The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.

So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?

You're trying to cherry pick fd9f578, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m option. For example, git cherry-pick -m 1 fd9f578 to use parent 1 as the base.

I can't say for sure for your particular situation, but using git merge instead of git cherry-pick is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

Exporting results of a Mysql query to excel?

The quick and dirty way I use to export mysql output to a file is

$ mysql <database_name> --tee=<file_path>

and then use the exported output (which you can find in <file_path>) wherever I want.

Note that this is the only way you have in order to avoid databases running using the secure-file-priv option, which prevents the usage of INTO OUTFILE suggested in the previous answers:

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

What is the difference between rb and r+b modes in file objects

My understanding is that adding r+ opens for both read and write (just like w+, though as pointed out in the comment, will truncate the file). The b just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

The only real difference is that a synchronized block can choose which object it synchronizes on. A synchronized method can only use 'this' (or the corresponding Class instance for a synchronized class method). For example, these are semantically equivalent:

synchronized void foo() {
  ...
}

void foo() {
    synchronized (this) {
      ...
    }
}

The latter is more flexible since it can compete for the associated lock of any object, often a member variable. It's also more granular because you could have concurrent code executing before and after the block but still within the method. Of course, you could just as easily use a synchronized method by refactoring the concurrent code into separate non-synchronized methods. Use whichever makes the code more comprehensible.

React onClick function fires on render

JSX will evaluate JavaScript expressions in curly braces

In this case, this.props.removeTaskFunction(todo) is invoked and the return value is assigned to onClick

What you have to provide for onClick is a function. To do this, you can wrap the value in an anonymous function.

export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
    const taskNodes = todoTasks.map(todo => (
                <div>
                    {todo.task}
                    <button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
                </div>
            );
    return (
        <div className="todo-task-list">
            {taskNodes}
        </div>
        );
    }
});

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

How do I change screen orientation in the Android emulator?

On Android Studio 4.0.1, the emulator includes buttons for rotation.

In the image below, the Rotate Left (shortcut: Ctrl + Left) button is outlined in blue and the Rotate Right (shortcut: Ctrl + Right) button is outlined in red.

Android Emulator

After pressing one of the buttons to rotate, the orientation of the application itself will not change. For instance, if we pressed Rotate Left, the application would look this:

Android Emulator Rotated Left

To change the orientation of the running application, it is necessary to click the icon outlined in red above. Note that this icon may take a few seconds to show up and will disappear shortly. Also, when rotating back to portrait orientation, one must press the opposite rotate button for the icon to appear. This means that if we pressed Rotate Left, we need to press Rotate Right to return to the original orientation, and vice versa.

Android Emulator Landscape

Jenkins: Can comments be added to a Jenkinsfile?

The official Jenkins documentation only mentions single line commands like the following:

// Declarative //

and (see)

pipeline {
    /* insert Declarative Pipeline here */
}

The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:

/* a standalone multiline comment
   spanning two lines */
println "hello" /* a multiline comment starting
                   at the end of a statement */
println 1 /* one */ + 2 /* two */

or

/**
 * such a nice comment
 */

How can I add 1 day to current date?

int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);

CodePen

_x000D_
_x000D_
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
_x000D_
_x000D_

Redirect website after certain amount of time

Here's a complete (yet simple) example of redirecting after X seconds, while updating a counter div:

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
    <div id="counter">5</div>_x000D_
    <script>_x000D_
        setInterval(function() {_x000D_
            var div = document.querySelector("#counter");_x000D_
            var count = div.textContent * 1 - 1;_x000D_
            div.textContent = count;_x000D_
            if (count <= 0) {_x000D_
                window.location.replace("https://example.com");_x000D_
            }_x000D_
        }, 1000);_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The initial content of the counter div is the number of seconds to wait.

How to write a confusion matrix in Python?

I wrote a simple class to build a confusion matrix without the need to depend on a machine learning library.

The class can be used such as:

labels = ["cat", "dog", "velociraptor", "kraken", "pony"]
confusionMatrix = ConfusionMatrix(labels)

confusionMatrix.update("cat", "cat")
confusionMatrix.update("cat", "dog")
...
confusionMatrix.update("kraken", "velociraptor")
confusionMatrix.update("velociraptor", "velociraptor")

confusionMatrix.plot()

The class ConfusionMatrix:

import pylab
import collections
import numpy as np


class ConfusionMatrix:
    def __init__(self, labels):
        self.labels = labels
        self.confusion_dictionary = self.build_confusion_dictionary(labels)

    def update(self, predicted_label, expected_label):
        self.confusion_dictionary[expected_label][predicted_label] += 1

    def build_confusion_dictionary(self, label_set):
        expected_labels = collections.OrderedDict()

        for expected_label in label_set:
            expected_labels[expected_label] = collections.OrderedDict()

            for predicted_label in label_set:
                expected_labels[expected_label][predicted_label] = 0.0

        return expected_labels

    def convert_to_matrix(self, dictionary):
        length = len(dictionary)
        confusion_dictionary = np.zeros((length, length))

        i = 0
        for row in dictionary:
            j = 0
            for column in dictionary:
                confusion_dictionary[i][j] = dictionary[row][column]
                j += 1
            i += 1

        return confusion_dictionary

    def get_confusion_matrix(self):
        matrix = self.convert_to_matrix(self.confusion_dictionary)
        return self.normalize(matrix)

    def normalize(self, matrix):
        amin = np.amin(matrix)
        amax = np.amax(matrix)

        return [[(((y - amin) * (1 - 0)) / (amax - amin)) for y in x] for x in matrix]

    def plot(self):
        matrix = self.get_confusion_matrix()

        pylab.figure()
        pylab.imshow(matrix, interpolation='nearest', cmap=pylab.cm.jet)
        pylab.title("Confusion Matrix")

        for i, vi in enumerate(matrix):
            for j, vj in enumerate(vi):
                pylab.text(j, i+.1, "%.1f" % vj, fontsize=12)

        pylab.colorbar()

        classes = np.arange(len(self.labels))
        pylab.xticks(classes, self.labels)
        pylab.yticks(classes, self.labels)

        pylab.ylabel('Expected label')
        pylab.xlabel('Predicted label')
        pylab.show()

How to allocate aligned memory only using the standard library?

For the solution i used a concept of padding which aligns the memory and do not waste the memory of a single byte .

If there are constraints that, you cannot waste a single byte. All pointers allocated with malloc are 16 bytes aligned.

C11 is supported, so you can just call aligned_alloc (16, size).

void *mem = malloc(1024+16);
void *ptr = ((char *)mem+16) & ~ 0x0F;
memset_16aligned(ptr, 0, 1024);
free(mem);

Python timedelta in years

I'll suggest Pyfdate

What is pyfdate?

Given Python's goal to be a powerful and easy-to-use scripting language, its features for working with dates and times are not as user-friendly as they should be. The purpose of pyfdate is to remedy that situation by providing features for working with dates and times that are as powerful and easy-to-use as the rest of Python.

the tutorial

Load jQuery with Javascript and use jQuery

You need to run your code AFTER jQuery finished loading

var script = document.createElement('script'); 
document.head.appendChild(script);    
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = function(){
    // your jQuery code here
} 

or if you're running it in an async function you could use await in the above code

var script = document.createElement('script'); 
document.head.appendChild(script);    
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
// your jQuery code here

If you want to check first if jQuery already exists in the page, try this

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I have a lib what use https://requests.readthedocs.io/en/master/ what use https://pypi.org/project/certifi/ but I have a custom CA included in my /etc/ssl/certs.

So I solved my problem like this:

# Your TLS certificates directory (Debian like)
export SSL_CERT_DIR=/etc/ssl/certs
# CA bundle PATH (Debian like again)
export CA_BUNDLE_PATH="${SSL_CERT_DIR}/ca-certificates.crt"
# If you have a virtualenv:
. ./.venv/bin/activate
# Get the current certifi CA bundle
CERTFI_PATH=`python -c 'import certifi; print(certifi.where())'`

test -L $CERTFI_PATH || rm $CERTFI_PATH
test -L $CERTFI_PATH || ln -s $CA_BUNDLE_PATH $CERTFI_PATH

Et voilĂ  !

Is header('Content-Type:text/plain'); necessary at all?

PHP uses Content-Type "text/html" as default - which is pretty similar to "text/plain" - and this explains why you don't see any differences. text/plain is necessary if you want to output text as is (including <>-symbols). Examples:

header("Content-Type: text/plain");
echo "<b>hello world</b>";
// Output: <b>hello world</b>

header("Content-Type: text/html");
echo "<b>hello world</b>";
// Output: hello world

How to convert all text to lowercase in Vim

Usually Vu (or VU for uppercase) is enough to turn the whole line into lowercase as V already selects the whole line to apply the action against.

Tilda (~) changes the case of the individual letter, resulting in camel case or the similar.

It is really great how Vim has many many different modes to deal with various occasions and how those modes are neatly organized.

For instance, v - the true visual mode, and the related V - visual line, and Ctrl+Q - visual block modes (what allows you to select blocks, a great feature some other advanced editors also offer usually by holding the Alt key and selecting the text).

Python Web Crawlers and "getting" html source code

If you are using Python > 3.x you don't need to install any libraries, this is directly built in the python framework. The old urllib2 package has been renamed to urllib:

from urllib import request

response = request.urlopen("https://www.google.com")
# set the correct charset below
page_source = response.read().decode('utf-8')
print(page_source)

How can I find my php.ini on wordpress?

Wordpress dont have a php.ini file. It just a cms, look into your server. for example if you use XAMPP in windows xampp\php\php.ini is the location.

Android - set TextView TextStyle programmatically?

So many way to achieve this task some are below:-

1.

String text_view_str = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!";
TextView tv = (TextView)findViewById(R.id.ur_text_view_id);
tv.setText(Html.fromHtml(text_view_str));

2.

tv.setTypeface(null, Typeface.BOLD);
tv.setTypeface(null, Typeface.ITALIC);
tv.setTypeface(null, Typeface.BOLD_ITALIC);
tv.setTypeface(null, Typeface.NORMAL);

3.

SpannableString spannablecontent=new SpannableString(o.content.toString());
spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 
                         0,spannablecontent.length(), 0);
// set Text here
tt.setText(spannablecontent);

4.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="boldText">
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">#FFFFFF</item>
    </style>

    <style name="normalText">
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">#C0C0C0</item>
    </style>

</resources>

 tv.setTextAppearance(getApplicationContext(), R.style.boldText);

or if u want through xml

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

How to get the HTML for a DOM element in javascript

var x = $('#container').get(0).outerHTML;

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
   // mobile content
}
else {
   // other content for desktops
}

Check if file exists and whether it contains a specific string

test -e will test whether a file exists or not. The test command returns a zero value if the test succeeds or 1 otherwise.

Test can be written either as test -e or using []

[ -e "$file_name" ] && grep "poet" $file_name

Unless you actually need the output of grep you can test the return value as grep will return 1 if there are no matches and zero if there are any.

In general terms you can test if a string is non-empty using [ "string" ] which will return 0 if non-empty and 1 if empty

How do I link to Google Maps with a particular longitude and latitude?

Using the query parameter won't work, Google will try to approximate the location.

The location I want : http://maps.google.com/maps?ll=43.7920533400153,6.37761393942265

The approximate location (west of the actual location) : http://maps.google.com/?q=43.7920533400153,6.37761393942265

Select the first row by group

What about

DT <- data.table(test)
setkey(DT, id)

DT[J(unique(id)), mult = "first"]

Edit

There is also a unique method for data.tables which will return the the first row by key

jdtu <- function() unique(DT)

I think, if you are ordering test outside the benchmark, then you can removing the setkey and data.table conversion from the benchmark as well (as the setkey basically sorts by id, the same as order).

set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]
DT <- data.table(DT, key = 'id')
ju <- function() test[!duplicated(test$id),]

jdt <- function() DT[J(unique(id)),mult = 'first']


 library(rbenchmark)
benchmark(ju(), jdt(), replications = 5)
##    test replications elapsed relative user.self sys.self 
## 2 jdt()            5    0.01        1      0.02        0        
## 1  ju()            5    0.05        5      0.05        0         

and with more data

** Edit with unique method**

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
DT <- data.table(test, key = 'id')
       test replications elapsed relative user.self sys.self 
2  jdt()            5    0.09     2.25      0.09     0.00    
3 jdtu()            5    0.04     1.00      0.05     0.00      
1   ju()            5    0.22     5.50      0.19     0.03        

The unique method is fastest here.

How do I set the default page of my application in IIS7?

On IIS Manager--> Http view--> double click on Default and write the name of your desired startup page, Thats it

Integer to hex string in C++

Thanks to Lincoln's comment below, I've changed this answer.

The following answer properly handles 8-bit ints at compile time. It doees, however, require C++17. If you don't have C++17, you'll have to do something else (e.g. provide overloads of this function, one for uint8_t and one for int8_t, or use something besides "if constexpr", maybe enable_if).

template< typename T >
std::string int_to_hex( T i )
{
    // Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
    static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");

    std::stringstream stream;
    stream << "0x" << std::setfill ('0') << std::setw(sizeof(T)*2) << std::hex;

    // If T is an 8-bit integer type (e.g. uint8_t or int8_t) it will be 
    // treated as an ASCII code, giving the wrong result. So we use C++17's
    // "if constexpr" to have the compiler decides at compile-time if it's 
    // converting an 8-bit int or not.
    if constexpr (std::is_same_v<std::uint8_t, T>)
    {        
        // Unsigned 8-bit unsigned int type. Cast to int (thanks Lincoln) to 
        // avoid ASCII code interpretation of the int. The number of hex digits 
        // in the  returned string will still be two, which is correct for 8 bits, 
        // because of the 'sizeof(T)' above.
        stream << static_cast<int>(i);
    }        
    else if (std::is_same_v<std::int8_t, T>)
    {
        // For 8-bit signed int, same as above, except we must first cast to unsigned 
        // int, because values above 127d (0x7f) in the int will cause further issues.
        // if we cast directly to int.
        stream << static_cast<int>(static_cast<uint8_t>(i));
    }
    else
    {
        // No cast needed for ints wider than 8 bits.
        stream << i;
    }

    return stream.str();
}

Original answer that doesn't handle 8-bit ints correctly as I thought it did:

Kornel Kisielewicz's answer is great. But a slight addition helps catch cases where you're calling this function with template arguments that don't make sense (e.g. float) or that would result in messy compiler errors (e.g. user-defined type).

template< typename T >
std::string int_to_hex( T i )
{
  // Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
  static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");

  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;

         // Optional: replace above line with this to handle 8-bit integers.
         // << std::hex << std::to_string(i);

  return stream.str();
}

I've edited this to add a call to std::to_string because 8-bit integer types (e.g. std::uint8_t values passed) to std::stringstream are treated as char, which doesn't give you the result you want. Passing such integers to std::to_string handles them correctly and doesn't hurt things when using other, larger integer types. Of course you may possibly suffer a slight performance hit in these cases since the std::to_string call is unnecessary.

Note: I would have just added this in a comment to the original answer, but I don't have the rep to comment.

Laravel Escaping All HTML in Blade Template

{{html_entity_decode ($post->content())}} saved the issue for me with Laravel 4.0. Now My HTML content is interpreted as it should.

How can I specify the required Node.js version in package.json?

There's another, simpler way to do this:

  1. npm install Node@8 (saves Node 8 as dependency in package.json)
  2. Your app will run using Node 8 for anyone - even Yarn users!

This works because node is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.

See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360

PHP upload image

Change function file_get_content() in your code to file_get_contents() . You are missing 's' at the end of function name. That is why it is giving undefined function error.

file_get_contents()

Remove last unnecessary comma after $image filed in line

"INSERT INTO content VALUES         ('','','','','','','','','','$image_name','$image',)

How to detect a docker daemon port

By default, the docker daemon will use the unix socket unix:///var/run/docker.sock (you can check this is the case for you by doing a sudo netstat -tunlp and note that there is no docker daemon process listening on any ports). It's recommended to keep this setting for security reasons but it sounds like Riak requires the daemon to be running on a TCP socket.

To start the docker daemon with a TCP socket that anybody can connect to, use the -H option:

sudo docker -H 0.0.0.0:2375 -d &

Warning: This means machines that can talk to the daemon through that TCP socket can get root access to your host machine.

Related docs:

http://basho.com/posts/technical/running-riak-in-docker/

https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections

What regular expression will match valid international phone numbers?

This Regex Expression works for India, Canada, Europe, New Zealand, Australia, United States phone numbers, along with their country codes:

"^(\+(([0-9]){1,2})[-.])?((((([0-9]){2,3})[-.]){1,2}([0-9]{4,10}))|([0-9]{10}))$"

How to examine processes in OS X's Terminal?

if you are using ps, you can check the manual

man ps

there is a list of keywords allowing you to build what you need. for example to show, userid / processid / percent cpu / percent memory / work queue / command :

ps -e -o "uid pid pcpu pmem wq comm"

-e is similar to -A (all inclusive; your processes and others), and -o is to force a format.

if you are looking for a specific uid, you can chain it using awk or grep such as :

ps -e -o "uid pid pcpu pmem wq comm" | grep 501

this should (almost) show only for userid 501. try it.

groovy: safely find a key in a map and return its value

Groovy maps can be used with the property property, so you can just do:

def x = mymap.likes

If the key you are looking for (for example 'likes.key') contains a dot itself, then you can use the syntax:

def x = mymap.'likes.key'

How can I format the output of a bash command in neat columns

Since AIX doesn't have a "column" command, I created the simplistic script below. It would be even shorter without the doc & input edits... :)

#!/usr/bin/perl
#       column.pl: convert STDIN to multiple columns on STDOUT
#       Usage: column.pl column-width number-of-columns  file...
#
$width = shift;
($width ne '') or die "must give column-width and number-of-columns\n";
$columns = shift;
($columns ne '') or die "must give number-of-columns\n";
($x = $width) =~ s/[^0-9]//g;
($x eq $width) or die "invalid column-width: $width\n";
($x = $columns) =~ s/[^0-9]//g;
($x eq $columns) or die "invalid number-of-columns: $columns\n";

$w = $width * -1; $c = $columns;
while (<>) {
        chomp;
        if ( $c-- > 1 ) {
                printf "%${w}s", $_;
                next;
        }
        $c = $columns;
        printf "%${w}s\n", $_;
}
print "\n";

How to use `subprocess` command with pipes

You can try the pipe functionality in sh.py:

import sh
print sh.grep(sh.ps("-ax"), "process_name")

Is there a way to programmatically scroll a scroll view to a specific edit text?

I think I have found more elegant and less error prone solution using

ScrollView.requestChildRectangleOnScreen

There is no math involved, and contrary to other proposed solutions, it will handle correctly scrolling both up and down.

/**
 * Will scroll the {@code scrollView} to make {@code viewToScroll} visible
 * 
 * @param scrollView parent of {@code scrollableContent}
 * @param scrollableContent a child of {@code scrollView} whitch holds the scrollable content (fills the viewport).
 * @param viewToScroll a child of {@code scrollableContent} to whitch will scroll the the {@code scrollView}
 */
void scrollToView(ScrollView scrollView, ViewGroup scrollableContent, View viewToScroll) {
    Rect viewToScrollRect = new Rect(); //coordinates to scroll to
    viewToScroll.getHitRect(viewToScrollRect); //fills viewToScrollRect with coordinates of viewToScroll relative to its parent (LinearLayout) 
    scrollView.requestChildRectangleOnScreen(scrollableContent, viewToScrollRect, false); //ScrollView will make sure, the given viewToScrollRect is visible
}

It is a good idea to wrap it into postDelayed to make it more reliable, in case the ScrollView is being changed at the moment

/**
 * Will scroll the {@code scrollView} to make {@code viewToScroll} visible
 * 
 * @param scrollView parent of {@code scrollableContent}
 * @param scrollableContent a child of {@code scrollView} whitch holds the scrollable content (fills the viewport).
 * @param viewToScroll a child of {@code scrollableContent} to whitch will scroll the the {@code scrollView}
 */
private void scrollToView(final ScrollView scrollView, final ViewGroup scrollableContent, final View viewToScroll) {
    long delay = 100; //delay to let finish with possible modifications to ScrollView
    scrollView.postDelayed(new Runnable() {
        public void run() {
            Rect viewToScrollRect = new Rect(); //coordinates to scroll to
            viewToScroll.getHitRect(viewToScrollRect); //fills viewToScrollRect with coordinates of viewToScroll relative to its parent (LinearLayout) 
            scrollView.requestChildRectangleOnScreen(scrollableContent, viewToScrollRect, false); //ScrollView will make sure, the given viewToScrollRect is visible
        }
    }, delay);
}

failed to open stream: No such file or directory in

It's because you have included a leading / in your file path. The / makes it start at the top of your filesystem. Note: filesystem path, not Web site path (you're not accessing it over HTTP). You can use a relative path with include_once (one that doesn't start with a leading /).

You can change it to this:

include_once 'headerSite.php';

That will look first in the same directory as the file that's including it (i.e. C:\xampp\htdocs\PoliticalForum\ in your example.

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Background

MD2 was widely recognized as insecure and thus disabled in Java in version JDK 6u17 (see release notes http://www.oracle.com/technetwork/java/javase/6u17-141447.html, "Disable MD2 in certificate chain validation"), as well as JDK 7, as per the configuration you pointed out in java.security.

Verisign was using a Class 3 root certificate with the md2WithRSAEncryption signature algorithm (serial 70:ba:e4:1d:10:d9:29:34:b6:38:ca:7b:03:cc:ba:bf), but deprecated it and replaced it with another certificate with the same key and name, but signed with algorithm sha1WithRSAEncryption. However, some servers are still sending the old MD2 signed certificate during the SSL handshake (ironically, I ran into this problem with a server run by Verisign!).

You can verify that this is the case by getting the certificate chain from the server and examining it:

openssl s_client -showcerts -connect <server>:<port>

Recent versions of the JDK (e.g. 6u21 and all released versions of 7) should resolve this issue by automatically removing certs with the same issuer and public key as a trusted anchor (in cacerts by default).

If you still have this issue with newer JDKs

Check if you have a custom trust manager implementing the older X509TrustManager interface. JDK 7+ is supposed to be compatible with this interface, however based on my investigation when the trust manager implements X509TrustManager rather than the newer X509ExtendedTrustManager (docs), the JDK uses its own wrapper (AbstractTrustManagerWrapper) and somehow bypasses the internal fix for this issue.

The solution is to:

  1. use the default trust manager, or

  2. modify your custom trust manager to extend X509ExtendedTrustManager directly (a simple change).

How can I set the aspect ratio in matplotlib?

you should try with figaspect. It works for me. From the docs:

Create a figure with specified aspect ratio. If arg is a number, use that aspect ratio. > If arg is an array, figaspect will determine the width and height for a figure that would fit array preserving aspect ratio. The figure width, height in inches are returned. Be sure to create an axes with equal with and height, eg

Example usage:

  # make a figure twice as tall as it is wide
  w, h = figaspect(2.)
  fig = Figure(figsize=(w,h))
  ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  ax.imshow(A, **kwargs)

  # make a figure with the proper aspect for an array
  A = rand(5,3)
  w, h = figaspect(A)
  fig = Figure(figsize=(w,h))
  ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  ax.imshow(A, **kwargs)

Edit: I am not sure of what you are looking for. The above code changes the canvas (the plot size). If you want to change the size of the matplotlib window, of the figure, then use:

In [68]: f = figure(figsize=(5,1))

this does produce a window of 5x1 (wxh).

Call Jquery function

Just add click event by jquery in $(document).ready() like :

$(document).ready(function(){

                  $('#YourControlID').click(function(){
                     if(Check your condtion)
                     {
                             $.messager.show({  
                                title:'My Title',  
                                msg:'The message content',  
                                showType:'fade',  
                                style:{  
                                    right:'',  
                                    bottom:''  
                                }  
                            });  
                     }
                 });
            });

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

Uninstall homebrew:

 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Then reinstall

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Warning: This script will remove: /Library/Caches/Homebrew/ - thks benjaminsila

Launch custom android application from android browser

Yeah, Chrome searches instead of looking for scheme. If you want to launch your App through URI scheme, use this cool utility App on the Play store. It saved my day :) https://play.google.com/store/apps/details?id=com.naosim.urlschemesender

Change bundle identifier in Xcode when submitting my first app in IOS

A very simple solution to that is to open the file:

YOURPROJECT.xcodeproj/project.pbxproj

And find for this variable:

PRODUCT_BUNDLE_IDENTIFIER

You'll see something like that:

PRODUCT_BUNDLE_IDENTIFIER = com.YOUR_APP_NAME.SOMETHING;

So, the name on the right is your Bundle Identifier. In my case it works perfectly.

Verify ImageMagick installation

This is as short and sweet as it can get:

if (!extension_loaded('imagick'))
    echo 'imagick not installed';

Best practices for Storyboard login screen, handling clearing of data upon logout

Here is what I ended up doing to accomplish everything. The only thing you need to consider in addition to this is (a) the login process and (b) where you are storing your app data (in this case, I used a singleton).

Storyboard showing login view controller and main tab controller

As you can see, the root view controller is my Main Tab Controller. I did this because after the user has logged in, I want the app to launch directly to the first tab. (This avoids any "flicker" where the login view shows temporarily.)

AppDelegate.m

In this file, I check whether the user is already logged in. If not, I push the login view controller. I also handle the logout process, where I clear data and show the login view.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Show login view if not logged in already
    if(![AppData isLoggedIn]) {
        [self showLoginScreen:NO];
    }

    return YES;
}

-(void) showLoginScreen:(BOOL)animated
{

    // Get login screen from storyboard and present it
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    LoginViewController *viewController = (LoginViewController *)[storyboard instantiateViewControllerWithIdentifier:@"loginScreen"];
    [self.window makeKeyAndVisible];
    [self.window.rootViewController presentViewController:viewController
                                             animated:animated
                                           completion:nil];
}

-(void) logout
{
    // Remove data from singleton (where all my app data is stored)
    [AppData clearData];

   // Reset view controller (this will quickly clear all the views)
   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
   MainTabControllerViewController *viewController = (MainTabControllerViewController *)[storyboard instantiateViewControllerWithIdentifier:@"mainView"];
   [self.window setRootViewController:viewController];

   // Show login screen
   [self showLoginScreen:NO];

}

LoginViewController.m

Here, if the login is successful, I simply dismiss the view and send a notification.

-(void) loginWasSuccessful
{

     // Send notification
     [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccessful" object:self];

     // Dismiss login screen
     [self dismissViewControllerAnimated:YES completion:nil];

}

Functional programming vs Object Oriented programming

You don't necessarily have to choose between the two paradigms. You can write software with an OO architecture using many functional concepts. FP and OOP are orthogonal in nature.

Take for example C#. You could say it's mostly OOP, but there are many FP concepts and constructs. If you consider Linq, the most important constructs that permit Linq to exist are functional in nature: lambda expressions.

Another example, F#. You could say it's mostly FP, but there are many OOP concepts and constructs available. You can define classes, abstract classes, interfaces, deal with inheritance. You can even use mutability when it makes your code clearer or when it dramatically increases performance.

Many modern languages are multi-paradigm.

Recommended readings

As I'm in the same boat (OOP background, learning FP), I'd suggest you some readings I've really appreciated: