Programs & Examples On #Typepad

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

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

At your parent DIV add

display:table;

and at your child element add

 display:table-cell;
 vertical-align:middle;

Single quotes vs. double quotes in C or C++

In C & C++ single quotes is known as a character ('a') whereas double quotes is know as a string ("Hello"). The difference is that a character can store anything but only one alphabet/number etc. A string can store anything. But also remember that there is a difference between '1' and 1. If you type cout<<'1'<<endl<<1; The output would be the same, but not in this case:

cout<<int('1')<<endl<<int(1);

This time the first line would be 48. As when you convert a character to an int it converts to its ascii and the ascii for '1' is 48. Same, if you do:

string s="Hi";
s+=48; //This will add "1" to the string
s+="1"; This will also add "1" to the string

How to create our own Listener interface in android?

Create listener interface.

public interface YourCustomListener
{
    public void onCustomClick(View view);
            // pass view as argument or whatever you want.
}

And create method setOnCustomClick in another activity(or fragment) , where you want to apply your custom listener......

  public void setCustomClickListener(YourCustomListener yourCustomListener)
{
    this.yourCustomListener= yourCustomListener;
}

Call this method from your First activity, and pass the listener interface...

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

Press any key to continue

Here is what I use.

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

How to change background and text colors in Sublime Text 3

I had the same issue. Sublime3 no longer shows all of the installed packages when you choose Show Packages from the Preferences Menu.

To customise a colour scheme do the following (UNIX):

  • Locate your SublimeText packages directory under the directory which SublimeText is installed in (in my setup this was /opt/sublime/Packages)
  • Open "Color Scheme - Default.sublime-package"
  • Choose the colour scheme which is closest to your requirements and copy it
  • From Sublime Text choose Preferences - Browse Packages - User
  • Paste the colour scheme you copied earlier here and rename it. It should now show up on your "Preferences - Color Scheme" menu under "User"
  • Follow the instructions at the link you previously mentioned to make the changes you require (Sublime 2 -changing background color based on file type?)

--- EDIT ---

For Mac OS X the themes are stored in zipped files so although the preferences file shows them as being in Packages/Color Scheme - Default/ they don't appear in that directory unless you extract them.

  • They can be extracted using the Package Resource Viewer (See this answer for how to install and use the Package Resource Viewer).
  • Search for Color Scheme in the Package Extractor (should give options for Color Scheme Default and Color Scheme legacy)
  • Extract the one you want. It will now be available at users/UserName/Library/Application Support/Sublime Text 3/Packages/Color Scheme - Default (or Legacy)
  • Make a copy of the scheme you want to modify, edit as needed and save it
  • Add or change the line in user preferences which points to the color scheme

for example

"color_scheme": "Packages/Color Scheme - Legacy/myTheme.tmTheme"

".addEventListener is not a function" why does this error occur?

Another important thing you need to note with ".addEventListener is not a function" error is that the error might be coming a result of assigning it a wrong object eg consider

let myImages = ['images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg'];
let i = 0;
while(i < myImages.length){
  const newImage = document.createElement('img');
  newImage.setAttribute('src',myImages[i]);
  thumbBar.appendChild(newImage);

 //Code just below will bring the said error 
 myImages[i].addEventListener('click',fullImage);

 //Code just below execute properly 
  newImage.addEventListener('click',fullImage);




  i++;
}

In the code Above I am basically assigning images to a div element in my html dynamically using javascript. I've done this by writing the images in an array and looping them through a while loop and adding all of them to the div element.

I've then added a click event listener for all images.

The code "myImages[i].addEventListener('click',fullImage);" will give you an error of "addEventListener is not a function" because I am chaining an addEventListener to an array object which does not have the addEventListener() function.

However for the code "newImage.addEventListener('click',fullImage);" it executes properly because the newImage object has access the function addEventListener() while the array object does not.

For more clarification follow the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function

Pass a JavaScript function as parameter

You can also use eval() to do the same thing.

//A function to call
function needToBeCalled(p1, p2)
{
    alert(p1+"="+p2);
}

//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
    eval(aFunction + "("+params+")");
}

//A function Call
callAnotherFunction("needToBeCalled", "10,20");

That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.

git still shows files as modified after adding to .gitignore

  1. Git add .

  2. Git status //Check file that being modified

    // git reset HEAD --- replace to which file you want to ignore

  3. git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!

  4. git commit -m ''

  5. git push

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

Is the URL that this code is making accessible in the browser?

http://" + Request.ServerVariables["HTTP_HOST"] + Request.ApplicationPath + "/PageDetails.aspx?ModuleID=" + ID

First thing you need to verify is that the URL you are making is correct. Then check in the browser to see if it is browsing. then use Fiddler tool to check what is passing over the network. It may be that URL that is being called through code is wrongly escaped.

Then check for firewall related issues.

How to change package name in flutter?

change in all AndroidManifest.xml files of your Flutter Project, --> package="your.name.app" (app/src/debug/AndroidManifest.xml) and (app/src/main/AndroidManifest.xml) and (app/src/profile/AndroidManifest.xml)

good look !!

Java 8 lambda get and remove element from list

As others have suggested, this might be a use case for loops and iterables. In my opinion, this is the simplest approach. If you want to modify the list in-place, it cannot be considered "real" functional programming anyway. But you could use Collectors.partitioningBy() in order to get a new list with elements which satisfy your condition, and a new list of those which don't. Of course with this approach, if you have multiple elements satisfying the condition, all of those will be in that list and not only the first.

How to parse JSON without JSON.NET library?

I use this...but have never done any metro app development, so I don't know of any restrictions on libraries available to you. (note, you'll need to mark your classes as with DataContract and DataMember attributes)

public static class JSONSerializer<TType> where TType : class
{
    /// <summary>
    /// Serializes an object to JSON
    /// </summary>
    public static string Serialize(TType instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(TType));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, instance);
            return Encoding.Default.GetString(stream.ToArray());
        }
    }

    /// <summary>
    /// DeSerializes an object from JSON
    /// </summary>
    public static TType DeSerialize(string json)
    {
        using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
        {
            var serializer = new DataContractJsonSerializer(typeof(TType));
            return serializer.ReadObject(stream) as TType;
        }
    }
}

So, if you had a class like this...

[DataContract]
public class MusicInfo
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Artist { get; set; }

    [DataMember]
    public string Genre { get; set; }

    [DataMember]
    public string Album { get; set; }

    [DataMember]
    public string AlbumImage { get; set; }

    [DataMember]
    public string Link { get; set; }

}

Then you would use it like this...

var musicInfo = new MusicInfo
{
     Name = "Prince Charming",
     Artist = "Metallica",
     Genre = "Rock and Metal",
     Album = "Reload",
     AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
     Link = "http://f2h.co.il/7779182246886"
};

// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);

// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);

Run Stored Procedure in SQL Developer?

Though this question is quite old, I keep stumbling into same result without finding an easy way to run from sql developer. After couple of tries, I found an easy way to execute the stored procedure from sql developer itself.

  • Under packages, select your desired package and right click on the package name (not on the stored procedure name).

  • You will find option to run. Select that and supply the required arguments. Click OK and you can see the output in output variables section below

I'm using SQL developer version 4.1.3.20

HTML5 validation when the input type is not "submit"

HTML5 Validation Work Only When button type will be submit

change --

<button type="button"  onclick="submitform()" id="save">Save</button>

To --

<button type="submit"  onclick="submitform()" id="save">Save</button>

Android emulator-5554 offline

In my case, the emulator was working with Oreo and lower, but not with Pie, and everything I tried seemed to have no effect. What finally worked was updating the emulator to latest (version 28).

How do you echo a 4-digit Unicode character in Bash?

In bash to print a Unicode character to output use \x,\u or \U (first for 2 digit hex, second for 4 digit hex, third for any length)

echo -e '\U1f602'

I you want to assign it to a variable use $'...' syntax

x=$'\U1f602'
echo $x

How to do an Integer.parseInt() for a decimal number?

0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.

Deleting multiple columns based on column names in Pandas

Not sure if this solution has been mentioned anywhere yet but one way to do is is pandas.Index.difference.

>>> df = pd.DataFrame(columns=['A','B','C','D'])
>>> df
Empty DataFrame
Columns: [A, B, C, D]
Index: []
>>> to_remove = ['A','C']
>>> df = df[df.columns.difference(to_remove)]
>>> df
Empty DataFrame
Columns: [B, D]
Index: []

Setting a PHP $_SESSION['var'] using jQuery

Similar to Luke's answer, but with GET.

Place this php-code in a php-page, ex. getpage.php:

<?php
$_SESSION['size'] = $_GET['size'];
?>

Then call it with a jQuery script like this:

$.get( "/getpage.php?size=1");

Agree with Federico. In some cases you may run into problems using POST, although not sure if it can be browser related.

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

How to find if element with specific id exists or not

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}

How to add class active on specific li on user click with jQuery

        // Remove active for all items.
        $('.sidebar-menu li').removeClass('active');
        // highlight submenu item
        $('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
        // Highlight parent menu item.
        $('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')

Android error: Failed to install *.apk on device *: timeout

I know it sounds silly, but after trying everything recomended for this timeout issue on when running on a device, I decided to try changing the cable and it worked. It's a Coby Kyros MID7015.

Trying another cable is a good and simple option to take a chance on.

Open Source Alternatives to Reflector?

The Reflector tool uses Reflection.  - apparently this is not correct.

You asked for two things - code that shows what reflector does, and also an alternative to reflector.

Here's an example, much simplified from what Reflector does, but it shows the technique of reflection: TypeView.cs

I don't have a suggestion for an open-source Reflector replacement.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

you can define it like this :

let table = $('.datatable-sales').DataTable({
        processing: true,
        responsive: true,
        serverSide: true,
        ajax: {
            url: "<?php echo site_url("your url"); ?>",
            cache: false,
            type: "POST",
            data: {
                <?php echo your api; ?>,
            }
        }

or like this :

$.get({url: <?php echo json_encode(site_url('your api'))?>, cache: false})

hope it helps

Get current application physical path within Application_Start

There's, however, slight difference among all these options which

I found out that

If you do

    string URL = Server.MapPath("~");

or

    string URL = Server.MapPath("/");

or

    string URL = HttpRuntime.AppDomainAppPath;

your URL will display resources in your link like this:

    "file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"

But if you want your URL to show only virtual path not the resources location, you should do

    string URL = HttpRuntime.AppDomainAppVirtualPath; 

then, your URL is displaying a virtual path to your resources as below

    "http://HOME/Index/bin/Resources/HandlerDoc.htm"        

List only stopped Docker containers

Only stopped containers can be listed using:

docker ps --filter "status=exited"

or

docker ps -f "status=exited"

How do I sort strings alphabetically while accounting for value when a string is numeric?

Just pad with zeroes to the same length:

int maxlen = sizes.Max(x => x.Length);
var result = sizes.OrderBy(x => x.PadLeft(maxlen, '0'));

How to catch a click event on a button?

All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.

An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.

package com.pointerunits.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
   private Button login;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      login = (Button)findViewById(R.id.loginbutton);
      login.setOnClickListener((OnClickListener) this);
      Log.i(DISPLAY_SERVICE, "Activity is created");

   }    

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {

      getMenuInflater().inflate(R.menu.main, menu);
      return true;
    }

   @Override
   public void onClick(View v) {
     Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
   }
}

Using Thymeleaf when the value is null

This can also be handled using the elvis operator ?: which will add a default value when the field is null:

<span th:text="${object.property} ?: 'default value'"></span>

Disable webkit's spin buttons on input type="number"?

I discovered that there is a second portion of the answer to this.

The first portion helped me, but I still had a space to the right of my type=number input. I had zeroed out the margin on the input, but apparently I had to zero out the margin on the spinner as well.

This fixed it:

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

Detecting Enter keypress on VB.NET

I'm using VB 2010 .NET 4.0 and use the following:

Private Sub tbSecurity_KeyPress(sender As System.Object, e As System.EventArgs) Handles tbSecurity.KeyPress
    Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
    If tmp.KeyChar = ChrW(Keys.Enter) Then
        MessageBox.Show("Enter key")
    Else
        MessageBox.Show(tmp.KeyChar)
    End If

End Sub

Works like a charm!

List files with certain extensions with ls and grep

No need for grep. Shell wildcards will do the trick.

ls *.mp4 *.mp3 *.exe

If you have run

shopt -s nullglob

then unmatched globs will be removed altogether and not be left on the command line unexpanded.

If you want case-insensitive globbing (so *.mp3 will match foo.MP3):

shopt -s nocaseglob

How to make an AJAX call without jQuery?

From youMightNotNeedJquery.com + JSON.stringify

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(JSON.stringify(data));

Enabling CORS in Cloud Functions for Firebase

No CORS solutions worked for me... till now!

Not sure if anyone else ran into the same issue I did, but I set up CORS like 5 different ways from examples I found and nothing seemed to work. I set up a minimal example with Plunker to see if it was really a bug, but the example ran beautifully. I decided to check the firebase functions logs (found in the firebase console) to see if that could tell me anything. I had a couple errors in my node server code, not CORS related, that when I debugged released me of my CORS error message. I don't know why code errors unrelated to CORS returns a CORS error response, but it led me down the wrong rabbit hole for a good number of hours...

tl;dr - check your firebase function logs if no CORS solutions work and debug any errros you have

Syntax for async arrow function

Async Arrow function syntax with parameters

const myFunction = async (a, b, c) => {
   // Code here
}

Display number with leading zeros

This is how I do it:

str(1).zfill(len(str(total)))

Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:

Python 3.6.5 (default, May 11 2018, 04:00:52) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>> 

How to create a simple map using JavaScript/JQuery

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

  1. First go through this tutorial for getting familiar with Android Google Maps and this for API 2.

  2. To retrive the current location of device see this answer or this another answer and for API 2

  3. Then you can get places near by your location using Google Place API and for use of Place Api see this blog.

  4. After getting Placemarks of near by location use this blog with source code to show markers on map with balloon overlay with API 2.

  5. You also have great sample to draw route between two points on map look here in these links Link1 and Link2 and this Great Answer.

After following these steps you will be easily able to do your application. The only condition is, you will have to read it and understand it, because like magic its not going to be complete in a click.

Pointers in JavaScript?

You refer to 'x' from window object

var x = 0;

function a(key, ref) {
    ref = ref || window;  // object reference - default window
    ref[key]++;
}

a('x');                   // string
alert(x);

How do you use math.random to generate random ints?

You can also use this way for getting random number between 1 and 100 as:

SecureRandom src=new SecureRandom();
int random=1 + src.nextInt(100);

How can you tell if a value is not numeric in Oracle?

The best answer I found on internet:

SELECT case when trim(TRANSLATE(col1, '0123456789-,.', ' ')) is null
            then 'numeric'
            else 'alpha'
       end
FROM tab1;

PHP foreach with Nested Array?

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

Parsing string as JSON with single quotes?

var str =  "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);
console.log(obj);

This solved the problem for me.

Javascript logical "!==" operator?

The !== opererator tests whether values are not equal or not the same type. i.e.

var x = 5;
var y = '5';
var 1 = y !== x; // true
var 2 = y != x; // false

How do I enumerate the properties of a JavaScript object?

Use a for..in loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.

var myObject = {foo: 'bar'};

for (var name in myObject) {
  alert(name);
}

// results in a single alert of 'foo'

Object.prototype.baz = 'quux';

for (var name in myObject) {
  alert(name);
}

// results in two alerts, one for 'foo' and one for 'baz'

To avoid including inherited properties in your enumeration, check hasOwnProperty():

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}

Edit: I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.

It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.

This is why JavaScript provides hasOwnProperty(), and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using hasOwnProperty().

Android: How do I get string from resources using its name?

If you don't have an Activity reference, you can use your context in this way:

getContext().getString(R.string.your_string_name);

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

Why have header files and .cpp files?

Responding to MadKeithV's answer,

This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times, and also the amount of recompilation needed when something in the implementation changes.

Another reason is that a header gives a unique id to each class.

So if we have something like

class A {..};
class B : public A {...};

class C {
    include A.cpp;
    include B.cpp;
    .....
};

We will have errors, when we try to build the project, since A is part of B, with headers we would avoid this kind of headache...

How to get main window handle from process id?

Old question but appears to have a lot of traffic, here is a simple solution:

IntPtr GetMainWindowHandle(IntPtr aHandle) {
        return System.Diagnostics.Process.GetProcessById(aHandle.ToInt32()).MainWindowHandle;
}

Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

_x000D_
_x000D_
// Example using a function expression
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: function() {
      console.log('Inside `bar`:', this.foo);
    },
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
// Example using a arrow function
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: () => console.log('Inside `bar`:', this.foo),
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
_x000D_
_x000D_

In the function expression case, this refers to the object that was created inside the createObject. In the arrow function case, this refers to this of createObject itself.

This makes arrow functions useful if you need to access the this of the current environment:

// currently common pattern
var that = this;
getData(function(data) {
  that.data = data;
});

// better alternative with arrow functions
getData(data => {
  this.data = data;
});

Note that this also means that is not possible to set an arrow function's this with .bind or .call.

If you are not very familiar with this, consider reading

2. Arrow functions cannot be called with new

ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).

Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable. class constructors are only constructable.

If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.


Knowing this, we can state the following.

Replaceable:

  • Functions that don't use this or arguments.
  • Functions that are used with .bind(this)

Not replaceable:

  • Constructor functions
  • Function / methods added to a prototype (because they usually use this)
  • Variadic functions (if they use arguments (see below))

Lets have a closer look at this using your examples:

Constructor function

This won't work because arrow functions cannot be called with new. Keep using a function declaration / expression or use class.

Prototype methods

Most likely not, because prototype methods usually use this to access the instance. If they don't use this, then you can replace it. However, if you primarily care for concise syntax, use class with its concise method syntax:

class User {
  constructor(name) {
    this.name = name;
  }
  
  getName() {
    return this.name;
  }
}

Object methods

Similarly for methods in an object literal. If the method wants to reference the object itself via this, keep using function expressions, or use the new method syntax:

const obj = {
  getName() {
    // ...
  },
};

Callbacks

It depends. You should definitely replace it if you are aliasing the outer this or are using .bind(this):

// old
setTimeout(function() {
  // ...
}.bind(this), 500);

// new
setTimeout(() => {
  // ...
}, 500);

But: If the code which calls the callback explicitly sets this to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this (or arguments), you cannot use an arrow function!

Variadic functions

Since arrow functions don't have their own arguments, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments: the rest parameter.

// old
function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// new
const sum = (...args) => {
  // ...
};

Related question:

Further resources:

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

Not sure whether you still have this issue. I had a similar issue and I was able to resolve it simply by unsetting PYTHONPATH

$ unset PYTHONPATH

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Pass all variables from one shell script to another?

Fatal Error gave a straightforward possibility: source your second script! if you're worried that this second script may alter some of your precious variables, you can always source it in a subshell:

( . ./test2.sh )

The parentheses will make the source happen in a subshell, so that the parent shell will not see the modifications test2.sh could perform.


There's another possibility that should definitely be referenced here: use set -a.

From the POSIX set reference:

-a: When this option is on, the export attribute shall be set for each variable to which an assignment is performed; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.21, Variable Assignment. If the assignment precedes a utility name in a command, the export attribute shall not persist in the current execution environment after the utility completes, with the exception that preceding one of the special built-in utilities causes the export attribute to persist after the built-in has completed. If the assignment does not precede a utility name in the command, or if the assignment is a result of the operation of the getopts or read utilities, the export attribute shall persist until the variable is unset.

From the Bash Manual:

-a: Mark variables and function which are modified or created for export to the environment of subsequent commands.

So in your case:

set -a
TESTVARIABLE=hellohelloheloo
# ...
# Here put all the variables that will be marked for export
# and that will be available from within test2 (and all other commands).
# If test2 modifies the variables, the modifications will never be
# seen in the present script!
set +a

./test2.sh

 # Here, even if test2 modifies TESTVARIABLE, you'll still have
 # TESTVARIABLE=hellohelloheloo

Observe that the specs only specify that with set -a the variable is marked for export. That is:

set -a
a=b
set +a
a=c
bash -c 'echo "$a"'

will echo c and not an empty line nor b (that is, set +a doesn't unmark for export, nor does it “save” the value of the assignment only for the exported environment). This is, of course, the most natural behavior.

Conclusion: using set -a/set +a can be less tedious than exporting manually all the variables. It is superior to sourcing the second script, as it will work for any command, not only the ones written in the same shell language.

Combine Date and Time columns using python pandas

Use the combine function:

datetime.datetime.combine(date, time)

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

A regex for version number parsing

My take on this, as a good exercise - vparse, which has a tiny source, with a simple function:

function parseVersion(v) {
    var m = v.match(/\d*\.|\d+/g) || [];
    v = {
        major: +m[0] || 0,
        minor: +m[1] || 0,
        patch: +m[2] || 0,
        build: +m[3] || 0
    };
    v.isEmpty = !v.major && !v.minor && !v.patch && !v.build;
    v.parsed = [v.major, v.minor, v.patch, v.build];
    v.text = v.parsed.join('.');
    return v;
}

Label on the left side instead above an input field

You can use a span tag inside the label

  <div class="form-group">
    <label for="rg-from">
      <span>Ab:</span> 
      <input type="text" id="rg-from" name="rg-from" value="" class="form-control">
    </label>
  </div>

Efficient way to do batch INSERTS with JDBC

In my code I have no direct access to the 'preparedStatement' so I cannot use batch, I just pass it the query and a list of parameters. The trick however is to create a variable length insert statement, and a LinkedList of parameters. The effect is the same as the top example, with variable parameter input length.See below (error checking omitted). Assuming 'myTable' has 3 updatable fields: f1, f2 and f3

String []args={"A","B","C", "X","Y","Z" }; // etc, input list of triplets
final String QUERY="INSERT INTO [myTable] (f1,f2,f3) values ";
LinkedList params=new LinkedList();
String comma="";
StringBuilder q=QUERY;
for(int nl=0; nl< args.length; nl+=3 ) { // args is a list of triplets values
    params.add(args[nl]);
    params.add(args[nl+1]);
    params.add(args[nl+2]);
    q.append(comma+"(?,?,?)");
    comma=",";
}      
int nr=insertIntoDB(q, params);

in my DBInterface class I have:

int insertIntoDB(String query, LinkedList <String>params) {
    preparedUPDStmt = connectionSQL.prepareStatement(query);
    int n=1;
    for(String x:params) {
        preparedUPDStmt.setString(n++, x);
    }
    int updates=preparedUPDStmt.executeUpdate();
    return updates;
}

How to get second-highest salary employees in a table

SELECT lastname, firstname
FROM employees
WHERE salary IN(
    SELECT MAX(salary) 
    FROM employees 
    WHERE salary < (SELECT MAX(salary) FROM employees));

So here is what the code mentioned above does:

It returns the last names followed by the first names of the employees that have a salary that is smaller than the max salary of all the employees but it's also the max salary of the rest employees that don't have the max salary.

In other words: It returns the names of the employees that have the second maximum salary.

Counting lines, words, and characters within a text file using Python

file__IO = input('\nEnter file name here to analize with path:: ')
with open(file__IO, 'r') as f:
    data = f.read()
    line = data.splitlines()
    words = data.split()
    spaces = data.split(" ")
    charc = (len(data) - len(spaces))

    print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces), '\n Charecters ::', (len(data)-len(spaces)))

I tried this code & it works as expected.

Error in eval(expr, envir, enclos) : object not found

This can happen if you don't attach your dataset.

How do I get LaTeX to hyphenate a word that contains a dash?

I use package hyphenat and then write compound words like Finnish word Internet-yhteys (Eng. Internet connection) as Internet\hyp yhteys. Looks goofy but seems to be the most elegant way I've found.

Running multiple commands with xargs

Another possible solution that works for me is something like -

cat a.txt | xargs bash -c 'command1 $@; command2 $@' bash

Note the 'bash' at the end - I assume it is passed as argv[0] to bash. Without it in this syntax the first parameter to each command is lost. It may be any word.

Example:

cat a.txt | xargs -n 5 bash -c 'echo -n `date +%Y%m%d-%H%M%S:` ; echo " data: " $@; echo "data again: " $@' bash

How do I position one image on top of another in HTML?

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

Windows batch script launch program and exit console

start "" "%SystemRoot%\Notepad.exe"

Keep the "" in between start and your application path.


Added explanation:

Normally when we launch a program from a batch file like below, we'll have the black windows at the background like OP said.

%SystemRoot%\Notepad.exe

This was cause by Notepad running in same command prompt (process). The command prompt will close AFTER notepad is closed. To avoid that, we can use the start command to start a separate process like this.

start %SystemRoot%\Notepad.exe

This command is fine as long it doesn't has space in the path. To handle space in the path for just in case, we added the " quotes like this.

start "%SystemRoot%\Notepad.exe"

However running this command would just start another blank command prompt. Why? If you lookup to the start /?, the start command will recognize the argument between the " as the title of the new command prompt it is going to launch. So, to solve that, we have the command like this:

start "" "%SystemRoot%\Notepad.exe"

The first argument of "" is to set the title (which we set as blank), and the second argument of "%SystemRoot%\Notepad.exe" is the target command to run (that support spaces in the path).

If you need to add parameters to the command, just append them quoted, i.e.:

start "" "%SystemRoot%\Notepad.exe" "<filename>" 

How to use Python's "easy_install" on Windows ... it's not so easy

For one thing, it says you already have that module installed. If you need to upgrade it, you should do something like this:

easy_install -U packageName

Of course, easy_install doesn't work very well if the package has some C headers that need to be compiled and you don't have the right version of Visual Studio installed. You might try using pip or distribute instead of easy_install and see if they work better.

Jquery Chosen plugin - dynamically populate list by Ajax

You can dynamically populate a list via AJAX using the excellent Select2 plugin. From my answer to "Is there a way to dynamically ajax add elements through jquery chosen plugin?":

Take a look at the neat Select2 plugin, which is based on Chosen itself and supports remote data sources (aka AJAX data) and infinite scrolling.

Reference — What does this symbol mean in PHP?

Magic constants: Although these are not just symbols but important part of this token family. There are eight magical constants that change depending on where they are used.

__LINE__: The current line number of the file.

__FILE__: The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.

__DIR__: The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)

__FUNCTION__: The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.

__CLASS__: The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.

__TRAIT__: The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).

__METHOD__: The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).

__NAMESPACE__: The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

Source

matplotlib: how to draw a rectangle on image

There is no need for subplots, and pyplot can display PIL images, so this can be simplified further:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image

im = Image.open('stinkbug.png')

# Display the image
plt.imshow(im)

# Get the current reference
ax = plt.gca()

# Create a Rectangle patch
rect = Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)

Or, the short version:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image

# Display the image
plt.imshow(Image.open('stinkbug.png'))

# Add the patch to the Axes
plt.gca().add_patch(Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none'))

How do you wait for input on the same Console.WriteLine() line?

Use Console.Write instead, so there's no newline written:

Console.Write("What is your name? ");
var name = Console.ReadLine();

How to get the Parent's parent directory in Powershell?

Version for a directory

get-item is your friendly helping hand here.

(get-item $scriptPath ).parent.parent

If you Want the string only

(get-item $scriptPath ).parent.parent.FullName

Version for a file

If $scriptPath points to a file then you have to call Directory property on it first, so the call would look like this

(get-item $scriptPath).Directory.Parent.Parent.FullName

Remarks
This will only work if $scriptPath exists. Otherwise you have to use Split-Path cmdlet.

Scrolling to element using webdriver?

There is another option to scroll page to required element if element has "id" attribute

If you want to navigate to page and scroll down to element with @id, it can be done automatically by adding #element_id to URL...

Example

Let's say we need to navigate to Selenium Waits documentation and scroll page down to "Implicit Wait" section. We can do

driver.get('https://selenium-python.readthedocs.io/waits.html')

and add code for scrolling...OR use

driver.get('https://selenium-python.readthedocs.io/waits.html#implicit-waits')

to navigate to page AND scroll page automatically to element with id="implicit-waits" (<div class="section" id="implicit-waits">...</div>)

Detect backspace and del on "input" event?

keydown with event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Modern style:

input.addEventListener('keydown', ({key}) => {
    if (["Backspace", "Delete"].includes(key)) {
        return false
    }
})

Mozilla Docs

Supported Browsers

Unable to load DLL 'SQLite.Interop.dll'

Could there be contention for the assembly? Check to see whether there's another application with a file lock on the DLL.

If this is the reason, it should be easy to use a tool like Sysinternal's Process Explorer to discover the offending program.

HTH, Clay

How to get the integer value of day of week

int day = (int)DateTime.Now.DayOfWeek;

First day of the week: Sunday (with a value of zero)

Display Python datetime without time

If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do

>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)

Note that this returns a new datetime object -- now remains unchanged.

"/usr/bin/ld: cannot find -lz"

I just encountered this problem and contrary to the accepted solution of "your make files are broken" and "host includes should never be included in a cross compile"

The android build includes many host executables used by the SDK to build an android app. In my case the make stopped while building zipalign, which is used to optimize an apk before installing on an android device.

Installing lib32z1-dev solved my problem, under Ubuntu you can install it with the following command:

sudo apt-get install lib32z1-dev

Java synchronized method lock on object, or method?

From oracle documentation link

Making methods synchronized has two effects:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads

Have a look at this documentation page to understand intrinsic locks and lock behavior.

This will answer your question: On same object x , you can't call x.addA() and x.addB() at same time when one of the synchronized methods execution is in progress.

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

Android: making a fullscreen application

I recently had the exact same issue and benefitted from the following post as well (in addition to Rohit5k2's solution above):

https://bsgconsultancy.wordpress.com/2015/09/13/convert-any-website-into-android-application-by-using-android-studio/

In Step 3, MainActivity extends Activity instead of ActionBarActivity (as Rohit5k2 mentioned). Putting the NoTitleBar and Fullscreen theme elements into the correct places in the AndroidManifest.xml file is also very important (take a look at Step 4).

Getting a link to go to a specific section on another page

I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID attribute. To support older browsers, you'll need to change:

<div id="timeline" name="timeline" ...>

To the old format:

<a name="timeline" />

You'll then be able to navigate to /academics/page.html#timeline and jump right to that section.

Also, check out this similar question.

Check that a variable is a number in UNIX shell

if echo $var | egrep -q '^[0-9]+$'; then
    # $var is a number
else
    # $var is not a number
fi

javascript pushing element at the beginning of an array

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

Delete from a table based on date

Delete data that is 30 days and older

   DELETE FROM Table
   WHERE DateColumn < GETDATE()- 30

Google Android USB Driver and ADB

Can you give us a better description and an example of what you are doing? Because all i have to do is put the line in there for the device and then save the file. Now just reconnect the device and it works.

I usually use something similar to this line:

;
;some name for the phone (this seems to be arbitrary)
%CompositeAdbInterface%     = USB_Install, THE_HARDWARE_ID

What i do, is:

  1. plug the device into the computer.
  2. Go to your device manager.
  3. Right click on the device that you plugged up.
  4. Go to properties. Then select Hardware Ids.
  5. Then get that value that is listed there.
  6. Now add it to the line you created in the android_winusb.inf.
  7. Unplug the device and plug back in
  8. Go back to the device manager
  9. Right click on the device and click update or install driver
  10. Select search your computer for the driver
  11. Select the directory Your_Android_SDK_Directory/extras/google/usb_driver/
  12. Press ok

That seems to always work for me, is that what you are doing? Or does this even help?

Mysql adding user for remote access

An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

My solution:

  1. remove all projects in current workspace
  2. import all again
  3. maven update project (Alt + F5) -> Select All and check Force Update of Snapshots/Releases
  4. maven build (Ctrl + B) until there is nothing to build

It worked for me after the second try.

How to upload a file in Django?

Demo

See the github repo, works with Django 3

A minimal Django file upload example

1. Create a django project

Run startproject::

$ django-admin.py startproject sample

now a folder(sample) is created.

2. create an app

Create an app::

$ cd sample
$ python manage.py startapp uploader

Now a folder(uploader) with these files are created::

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3. Update settings.py

On sample/settings.py add 'uploader' to INSTALLED_APPS and add MEDIA_ROOT and MEDIA_URL, ie::

INSTALLED_APPS = [
    'uploader',
    ...<other apps>...      
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. Update urls.py

in sample/urls.py add::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update models.py

update uploader/models.py::

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. Update views.py

update uploader/views.py::

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. create templates

Create a folder sample/uploader/templates/uploader

Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    </form><hr>
    <ul>
    {% for document in documents %}
        <li>
            <a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
        </li>
    {% endfor %}
    </ul>
</div>

8. Syncronize database

Syncronize database and runserver::

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

visit http://localhost:8000/

Which command in VBA can count the number of characters in a string variable?

Len(word)

Although that's not what your question title asks =)

Why do we always prefer using parameters in SQL statements?

Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface such as a desktop program or web site.

In your example, a user can directly run SQL code on your database by crafting statements in txtSalary.

For example, if they were to write 0 OR 1=1, the executed SQL would be

 SELECT empSalary from employee where salary = 0 or 1=1

whereby all empSalaries would be returned.

Further, a user could perform far worse commands against your database, including deleting it If they wrote 0; Drop Table employee:

SELECT empSalary from employee where salary = 0; Drop Table employee

The table employee would then be deleted.


In your case, it looks like you're using .NET. Using parameters is as easy as:

    string sql = "SELECT empSalary from employee where salary = @salary";

    using (SqlConnection connection = new SqlConnection(/* connection info */))
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        var salaryParam = new SqlParameter("salary", SqlDbType.Money);
        salaryParam.Value = txtMoney.Text;
    
        command.Parameters.Add(salaryParam);
        var results = command.ExecuteReader();
    }

    Dim sql As String = "SELECT empSalary from employee where salary = @salary"
    Using connection As New SqlConnection("connectionString")
        Using command As New SqlCommand(sql, connection)
            Dim salaryParam = New SqlParameter("salary", SqlDbType.Money)
            salaryParam.Value = txtMoney.Text
    
            command.Parameters.Add(salaryParam)

            Dim results = command.ExecuteReader()
        End Using
    End Using

Edit 2016-4-25:

As per George Stocker's comment, I changed the sample code to not use AddWithValue. Also, it is generally recommended that you wrap IDisposables in using statements.

Access key value from Web.config in Razor View-MVC3 ASP.NET

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }

How to replace a string in an existing file in Perl?

$_='~s/blue/red/g';

Uh, what??

Just

s/blue/red/g;

or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

$_ =~ s/blue/red/g;

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

How to switch between hide and view password

You can use app:passwordToggleEnabled="true"

here is example given below

<android.support.design.widget.TextInputLayout
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleEnabled="true"
        android:textColorHint="@color/colorhint"
        android:textColor="@color/colortext">

How can I change UIButton title color?

Solution in Swift 3:

button.setTitleColor(UIColor.red, for: .normal)

This will set the title color of button.

how to save and read array of array in NSUserdefaults in swift?

The question reads "array of array" but I think most people probably come here just wanting to know how to save an array to UserDefaults. For those people I will add a few common examples.

String array

Save array

let array = ["horse", "cow", "camel", "sheep", "goat"]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")

Retrieve array

let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()

Int array

Save array

let array = [15, 33, 36, 723, 77, 4]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedIntArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedIntArray")  as? [Int] ?? [Int]()

Bool array

Save array

let array = [true, true, false, true, false]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedBoolArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedBoolArray")  as? [Bool] ?? [Bool]()

Date array

Save array

let array = [Date(), Date(), Date(), Date()]

let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedDateArray")

Retrieve array

let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedDateArray")  as? [Date] ?? [Date]()

Object array

Custom objects (and consequently arrays of objects) take a little more work to save to UserDefaults. See the following links for how to do it.

Notes

  • The nil coalescing operator (??) allows you to return the saved array or an empty array without crashing. It means that if the object returns nil, then the value following the ?? operator will be used instead.
  • As you can see, the basic setup was the same for Int, Bool, and Date. I also tested it with Double. As far as I know, anything that you can save in a property list will work like this.

Storing a file in a database as opposed to the file system?

Not to be vague or anything but I think the type of 'file' you will be storing is one of the biggest determining factors. If you essentially talking about a large text field which could be stored as file my preference would be for db storage.

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

How to dump a dict to a json file?

Combine the answer of @mgilson and @gnibbler, I found what I need was this:


d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()

It this way, I got a pretty-print json file. The tricks print >> f, j is found from here: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/

Change arrow colors in Bootstraps carousel

To customize the colors for the carousel controls, captions, and indicators using Sass you can include these variables

    $carousel-control-color: 
    $carousel-caption-color: 
    $carousel-indicator-active-bg: 

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

How do I display Ruby on Rails form validation error messages one at a time?

ActiveRecord stores validation errors in an array called errors. If you have a User model then you would access the validation errors in a given instance like so:

@user = User.create[params[:user]] # create will automatically call validators

if @user.errors.any? # If there are errors, do something

  # You can iterate through all messages by attribute type and validation message
  # This will be something like:
  # attribute = 'name'
  # message = 'cannot be left blank'
  @user.errors.each do |attribute, message|
    # do stuff for each error
  end

  # Or if you prefer, you can get the full message in single string, like so:
  # message = 'Name cannot be left blank'
  @users.errors.full_messages.each do |message|
    # do stuff for each error
  end

  # To get all errors associated with a single attribute, do the following:
  if @user.errors.include?(:name)
    name_errors = @user.errors[:name]

    if name_errors.kind_of?(Array)
      name_errors.each do |error|
        # do stuff for each error on the name attribute
      end
    else
      error = name_errors
      # do stuff for the one error on the name attribute.
    end
  end
end

Of course you can also do any of this in the views instead of the controller, should you want to just display the first error to the user or something.

How to check Django version

For checking using a Python shell, do the following.

>>>from django import get_version
>>> get_version()

If you wish to do it in Unix/Linux shell with a single line, then do

python -c 'import django; print(django.get_version())'

Once you have developed an application, then you can check version directly using the following.

python manage.py runserver --version

Java HashMap performance optimization / alternative

Another poster already pointed out that your hashcode implementation will result in a lot of collisions due to the way that you're adding values together. I'm willing to be that, if you look at the HashMap object in a debugger, you'll find that you have maybe 200 distinct hash values, with extremely long bucket chains.

If you always have values in the range 0..51, each of those values will take 6 bits to represent. If you always have 5 values, you can create a 30-bit hashcode with left-shifts and additions:

    int code = a[0];
    code = (code << 6) + a[1];
    code = (code << 6) + b[0];
    code = (code << 6) + b[1];
    code = (code << 6) + b[2];
    return code;

The left-shift is fast, but will leave you with hashcodes that aren't evenly distributed (because 6 bits implies a range 0..63). An alternative is to multiply the hash by 51 and add each value. This still won't be perfectly distributed (eg, {2,0} and {1,52} will collide), and will be slower than the shift.

    int code = a[0];
    code *= 51 + a[1];
    code *= 51 + b[0];
    code *= 51 + b[1];
    code *= 51 + b[2];
    return code;

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Find records from one table which don't exist in another

SELECT DISTINCT Call.id 
FROM Call 
LEFT OUTER JOIN Phone_book USING (id) 
WHERE Phone_book.id IS NULL

This will return the extra id-s that are missing in your Phone_book table.

Set default format of datetimepicker as dd-MM-yyyy

You could easily use:

label1.Text = dateTimePicker1.Value.Date.ToString("dd/MM/yyyy")

and if you want to change '/' or '-', just add this:

label1.Text = label1.Text.Replace(".", "-")

More info about DateTimePicker.CustomFormat Property: Link

Extract hostname name from string

All url properties, no dependencies, no JQuery, easy to understand

This solution gives your answer plus additional properties. No JQuery or other dependencies required, paste and go.

Usage

getUrlParts("https://news.google.com/news/headlines/technology.html?ned=us&hl=en")

Output

{
  "origin": "https://news.google.com",
  "domain": "news.google.com",
  "subdomain": "news",
  "domainroot": "google.com",
  "domainpath": "news.google.com/news/headlines",
  "tld": ".com",
  "path": "news/headlines/technology.html",
  "query": "ned=us&hl=en",
  "protocol": "https",
  "port": 443,
  "parts": [
    "news",
    "google",
    "com"
  ],
  "segments": [
    "news",
    "headlines",
    "technology.html"
  ],
  "params": [
    {
      "key": "ned",
      "val": "us"
    },
    {
      "key": "hl",
      "val": "en"
    }
  ]
}

Code
The code is designed to be easy to understand rather than super fast. It can be called easily 100 times per second, so it's great for front end or a few server usages, but not for high volume throughput.

function getUrlParts(fullyQualifiedUrl) {
    var url = {},
        tempProtocol
    var a = document.createElement('a')
    // if doesn't start with something like https:// it's not a url, but try to work around that
    if (fullyQualifiedUrl.indexOf('://') == -1) {
        tempProtocol = 'https://'
        a.href = tempProtocol + fullyQualifiedUrl
    } else
        a.href = fullyQualifiedUrl
    var parts = a.hostname.split('.')
    url.origin = tempProtocol ? "" : a.origin
    url.domain = a.hostname
    url.subdomain = parts[0]
    url.domainroot = ''
    url.domainpath = ''
    url.tld = '.' + parts[parts.length - 1]
    url.path = a.pathname.substring(1)
    url.query = a.search.substr(1)
    url.protocol = tempProtocol ? "" : a.protocol.substr(0, a.protocol.length - 1)
    url.port = tempProtocol ? "" : a.port ? a.port : a.protocol === 'http:' ? 80 : a.protocol === 'https:' ? 443 : a.port
    url.parts = parts
    url.segments = a.pathname === '/' ? [] : a.pathname.split('/').slice(1)
    url.params = url.query === '' ? [] : url.query.split('&')
    for (var j = 0; j < url.params.length; j++) {
        var param = url.params[j];
        var keyval = param.split('=')
        url.params[j] = {
            'key': keyval[0],
            'val': keyval[1]
        }
    }
    // domainroot
    if (parts.length > 2) {
        url.domainroot = parts[parts.length - 2] + '.' + parts[parts.length - 1];
        // check for country code top level domain
        if (parts[parts.length - 1].length == 2 && parts[parts.length - 1].length == 2)
            url.domainroot = parts[parts.length - 3] + '.' + url.domainroot;
    }
    // domainpath (domain+path without filenames) 
    if (url.segments.length > 0) {
        var lastSegment = url.segments[url.segments.length - 1]
        var endsWithFile = lastSegment.indexOf('.') != -1
        if (endsWithFile) {
            var fileSegment = url.path.indexOf(lastSegment)
            var pathNoFile = url.path.substr(0, fileSegment - 1)
            url.domainpath = url.domain
            if (pathNoFile)
                url.domainpath = url.domainpath + '/' + pathNoFile
        } else
            url.domainpath = url.domain + '/' + url.path
    } else
        url.domainpath = url.domain
    return url
}

Selecting Values from Oracle Table Variable / Array?

In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.

So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:

CREATE OR REPLACE TYPE array is table of number;
/

Then you can use it as in these two examples within PL/SQL:

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    for i in (select level from dual connect by level < 10) loop
  5      p.extend;
  6      p(p.count) := i.level;
  7    end loop;
  8    for x in (select column_value from table(cast(p as array))) loop
  9       dbms_output.put_line(x.column_value);
 10    end loop;
 11* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    select level bulk collect into p from dual connect by level < 10;
  5    for x in (select column_value from table(cast(p as array))) loop
  6       dbms_output.put_line(x.column_value);
  7    end loop;
  8* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

Additional example based on comments

Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.

CREATE OR REPLACE PACKAGE p_cache AS
  FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/

CREATE OR REPLACE PACKAGE BODY p_cache AS

  cache_array  array;

  FUNCTION get_p_cursor RETURN sys_refcursor IS
    pCursor  sys_refcursor;
  BEGIN
    OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
    RETURN pCursor;
  END get_p_cursor;

  -- Package initialization runs once in each session that references the package
  BEGIN
    SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
  END p_cache;
/

How to insert new cell into UITableView in Swift

For Swift 5

Remove Cell

    let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
    yourArray.remove(at: buttonTag)
    self.tableView.beginUpdates()

    self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
    self.tableView.endUpdates()
    self.tableView.reloadData()// Not mendatory, But In my case its requires

Add new cell

    yourArray.append(4)

    tableView.beginUpdates()
    tableView.insertRows(at: [
        (NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
    tableView.endUpdates()

Query to check index on a table

Most modern RDBMSs support the INFORMATION_SCHEMA schema. If yours supports that, then you want either INFORMATION_SCHEMA.TABLE_CONSTRAINTS or INFORMATION_SCHEMA.KEY_COLUMN_USAGE, or maybe both.

To see if yours supports it is as simple as running

select count(*) from INFORMATION_SCHEMA.TABLE_CONSTRAINTS

EDIT: SQL Server does have INFORMATION_SCHEMA, and it's easier to use than their vendor-specific tables, so just go with it.

How to check if a text field is empty or not in swift

I just tried to show you the solution in a simple code

@IBAction func Button(sender : AnyObject) {
 if textField1.text != "" {
   // either textfield 1 is not empty then do this task
 }else{
   //show error here that textfield1 is empty
 }
}

My Application Could not open ServletContext resource

I encountered this exception in WebLogic, turns out it is a bug in WebLogic. Please see here for more details: Spring Boot exception: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

How to sort a dataframe by multiple column(s)

Just for the sake of completeness, since not much has been said about sorting by column numbers... It can surely be argued that it is often not desirable (because the order of the columns could change, paving the way to errors), but in some specific situations (when for instance you need a quick job done and there is no such risk of columns changing orders), it might be the most sensible thing to do, especially when dealing with large numbers of columns.

In that case, do.call() comes to the rescue:

ind <- do.call(what = "order", args = iris[,c(5,1,2,3)])
iris[ind, ]

##        Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
##    14           4.3         3.0          1.1         0.1     setosa
##    9            4.4         2.9          1.4         0.2     setosa
##    39           4.4         3.0          1.3         0.2     setosa
##    43           4.4         3.2          1.3         0.2     setosa
##    42           4.5         2.3          1.3         0.3     setosa
##    4            4.6         3.1          1.5         0.2     setosa
##    48           4.6         3.2          1.4         0.2     setosa
##    7            4.6         3.4          1.4         0.3     setosa
##    (...)

Array of arrays (Python/NumPy)

It seems strange that you would write arrays without commas (is that a MATLAB syntax?)

Have you tried going through NumPy's documentation on multi-dimensional arrays?

It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:

>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)

>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])

It has also been answered already...

From the documentation for MATLAB users:

You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:

mat("1 2 3; 4 5 6")

or

matrix("[1 2 3; 4 5 6]")

Please give it a try and tell me how it goes.

How can I develop for iPhone using a Windows development machine?

You can install OSX on PC but experience wont be great and it needs lot of work. Alternate is to use a framework/SDK Codename one: which is based on JAVA and can be used to code in WP8, Android, iOS on Windows (eclipse) with all extensive features

Features Overview:

  1. Full Android environment with super fast android simulator
  2. An iPhone/iPad simulator with easy to take iPhone apps to large screen iPad in minutes.
  3. Full support for standard java debugging, profiling for apps on any platform.
  4. Easy themeing / styling – Only a click away

More at Develop Android, iOS iPhone, WP8 apps using Java Disclaimer: This is my review for the product

Add new element to an existing object

Just do myFunction.foo = "bar" and it will add it. myFunction is the name of the object in this case.

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

How to specify the download location with wget?

-O is the option to specify the path of the file you want to download to:

wget <uri> -O /path/to/file.ext

-P is prefix where it will download the file in the directory:

wget <uri> -P /path/to/folder

Use jQuery to change a second select list based on the first select list option

I wanted to make a version of this that uses $.getJSON() from a separate JSON file.

Demo: here

JavaScript:

$(document).ready(function () {
    "use strict";

    var selectData, $states;

    function updateSelects() {
        var cities = $.map(selectData[this.value], function (city) {
            return $("<option />").text(city);
        });
        $("#city_names").empty().append(cities);
    }

    $.getJSON("updateSelect.json", function (data) {
        var state;
        selectData = data;
        $states = $("#us_states").on("change", updateSelects);
        for (state in selectData) {
            $("<option />").text(state).appendTo($states);
        }
        $states.change();
    });
});

HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <select id="us_states"></select>
    <select id="city_names"></select>
    <script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>

JSON:

{
    "NE": [
        "Smallville",
        "Bigville"
    ],
    "CA": [
        "Sunnyvale",
        "Druryburg",
        "Vickslake"
    ],
    "MI": [
        "Lakeside",
        "Fireside",
        "Chatsville"
    ]
}

How do I tell a Python script to use a particular version

Perhaps not exactly what you asked, but I find this to be useful to put at the start of my programs:

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

Change background color of iframe issue

just building on what Chetabahana wrote, I found that adding a short delay to the JS function helped on a site I was working on. It meant that the function kicked in after the iframe loaded. You can play around with the delay.

var delayInMilliseconds = 500; // half a second

setTimeout(function() { 

   var iframe = document.getElementsByTagName('iframe')[0];
   iframe.style.background = 'white';
   iframe.contentWindow.document.body.style.backgroundColor = 'white';

}, delayInMilliseconds);

I hope this helps!

Add Insecure Registry to Docker

For me the solution was to add the registry to here:

/etc/sysconfig/docker-registries

DOCKER_REGISTRIES=''
DOCKER_EXTRA_REGISTRIES='--insecure-registry  b.example.com'

Order a MySQL table by two columns

This maybe help somebody who is looking for the way to sort table by two columns, but in paralel way. This means to combine two sorts using aggregate sorting function. It's very useful when for example retrieving articles using fulltext search and also concerning the article publish date.

This is only example, but if you catch the idea you can find a lot of aggregate functions to use. You can even weight the columns to prefer one over second. The function of mine takes extremes from both sorts, thus the most valued rows are on the top.

Sorry if there exists simplier solutions to do this job, but I haven't found any.

SELECT
 `id`,
 `text`,
 `date`
 FROM
   (
   SELECT
     k.`id`,
     k.`text`,
     k.`date`,
     k.`match_order_id`,
     @row := @row + 1 as `date_order_id`
     FROM
     (
       SELECT
         t.`id`,
         t.`text`,
         t.`date`,
         @row := @row + 1 as `match_order_id`
         FROM
         (
           SELECT
             `art_id` AS `id`,
             `text`   AS `text`,
             `date`   AS `date`,
             MATCH (`text`) AGAINST (:string) AS `match`
             FROM int_art_fulltext
             WHERE MATCH (`text`) AGAINST (:string IN BOOLEAN MODE)
             LIMIT 0,101
         ) t,
         (
           SELECT @row := 0
         ) r
         ORDER BY `match` DESC
     ) k,
     (
       SELECT @row := 0
     ) l
     ORDER BY k.`date` DESC
   ) s
 ORDER BY (1/`match_order_id`+1/`date_order_id`) DESC

How to calculate combination and permutation in R?

The function combn is in the standard utils package (i.e. already installed)

choose is also already available in the Special {base}

View array in Visual Studio debugger?

Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.

If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

This is new way to do this using https://github.com/k06a/ABStaticTableViewController

NSIndexPath *ip = [NSIndexPath indexPathForRow:1 section:1];
[self deleteRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationFade]

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

I get that problem in the past. I'm using PostgreSQL and when I run my program, sometimes it connects and sometimes it throws an error like that.

When I experiment with my code, I put my Connection code at the very first line below the public Form. Here is an example:

BEFORE:

    public Form1()
        {
        //HERE LIES SOME CODES FOR RESIZING MY CONTROLS DURING RUNTIME
        //CODE
        //CODE AGAIN
        //ANOTHER CODE
        //CODE NA NAMAN
        //CODE PA RIN!





        //Connect to Database to generate auto number
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=pass;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand("Select * from table1", iConnect);
        NpgsqlDataReader iRead = iQuery.ExecuteReader();
        NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

        DataSet iDataSet = new DataSet();
        iAdapter.Fill(iDataSet, "ID");

        MessageBox.Show(iDataSet.Tables["ID"].Rows.Count.ToString());
        }

NOW:

    public Form1()
        {
        //Connect to Database to generate auto number
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=pass;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand("Select * from table1", iConnect);
        NpgsqlDataReader iRead = iQuery.ExecuteReader();
        NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

        DataSet iDataSet = new DataSet();
        iAdapter.Fill(iDataSet, "ID");

        MessageBox.Show(iDataSet.Tables["ID"].Rows.Count.ToString());





        //HERE LIES SOME CODES FOR RESIZING MY CONTROLS DURING RUNTIME
        //CODE
        //CODE AGAIN
        //ANOTHER CODE
        //CODE NA NAMAN
        //CODE PA RIN!

        }

I think that the program must read first the connection before doing anything, I don't know, correct me if I'm wrong. But according to my research, it's not a code problem - it was actually from the machine itself.

Happy Coding!

How to insert text in a td with id, using JavaScript

<html>

<head>
<script type="text/javascript">
function insertText () {
    document.getElementById('td1').innerHTML = "Some text to enter";
}
</script>
</head>

<body onload="insertText();">
    <table>
        <tr>
            <td id="td1"></td>
        </tr>
    </table>
</body>
</html>

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

How can I combine multiple rows into a comma-delimited list in Oracle?

The fastest way it is to use the Oracle collect function.

You can also do this:

select *
  2    from (
  3  select deptno,
  4         case when row_number() over (partition by deptno order by ename)=1
  5             then stragg(ename) over
  6                  (partition by deptno
  7                       order by ename
  8                         rows between unbounded preceding
  9                                  and unbounded following)
 10         end enames
 11    from emp
 12         )
 13   where enames is not null

Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.

Log to the base 2 in python

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

Select the values of one property on all objects of an array in PowerShell

As an even easier solution, you could just use:

$results = $objects.Name

Which should fill $results with an array of all the 'Name' property values of the elements in $objects.

How to implement zoom effect for image view in android?

Below is the code for ImageFullViewActivity Class

 public class ImageFullViewActivity extends AppCompatActivity {

        private ScaleGestureDetector mScaleGestureDetector;
        private float mScaleFactor = 1.0f;
        private ImageView mImageView;

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

            mImageView = (ImageView) findViewById(R.id.imageView);
            mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());

        }

        @Override
        public boolean onTouchEvent(MotionEvent motionEvent) {
            mScaleGestureDetector.onTouchEvent(motionEvent);
            return true;
        }

        private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
            @Override
            public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
                mScaleFactor *= scaleGestureDetector.getScaleFactor();
                mScaleFactor = Math.max(0.1f,
                        Math.min(mScaleFactor, 10.0f));
                mImageView.setScaleX(mScaleFactor);
                mImageView.setScaleY(mScaleFactor);
                return true;
            }
        }
    }

Align div right in Bootstrap 3

i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right only push the div to the right, but not the content inside the div.

HTML:

<div class="row">
  <div class="container">
    <div class="col-md-4 someclass">
      left content
    </div>
    <div class="col-md-4 col-md-offset-4 someclass">
      <div class="yellow_background totheright">right content</div>
    </div>
  </div>
</div>

CSS:

.someclass{ /*this class for testing purpose only*/
    border:1px solid blue;
    line-height:2em;
}

.totheright{ /*this will align the text to the right*/
  text-align:right;
}

.yellow_background{
    background-color:yellow;
}

Another modification:

...
<div class="yellow_background totheright">
  <span>right content</span>
  <br/>image also align-right<br/>
  <img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...

hope it will clear your problem

How to specify jackson to only use fields - preferably globally

If you use Spring Boot, you can configure Jackson globally as follows:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonObjectMapperConfiguration implements Jackson2ObjectMapperBuilderCustomizer {

    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        jacksonObjectMapperBuilder.visibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        jacksonObjectMapperBuilder.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        jacksonObjectMapperBuilder.visibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY);
    }

}

curl.h no such file or directory

Instead of downloading curl, down libcurl.

curl is just the application, libcurl is what you need for your C++ program

http://packages.ubuntu.com/quantal/curl

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

Let's start with a simple example. Let's say you have an email list, that is going to send out the following RFC2822 content.

From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's say you are going to send it from a mailing list, that implements VERP (or some other bounce tracking mechanism that uses a different return-path). Lets say it will have a return-path of [email protected]. The SMTP session might look like:

{S}220 workstation1 Microsoft ESMTP MAIL Service
{C}HELO workstation1
{S}250 workstation1 Hello [127.0.0.1]
{C}MAIL FROM:<[email protected]>
{S}250 2.1.0 [email protected] OK
{C}RCPT TO:<[email protected]>
{S}250 2.1.5 [email protected] 
{C}DATA
{S}354 Start mail input; end with <CRLF>.<CRLF>
{C}From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.
.

{S}250 Queued mail for delivery
{C}QUIT
{S}221 Service closing transmission channel

Where {C} and {S} represent Client and Server commands, respectively.

The recipient's mail would look like:

Return-Path: [email protected]
From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's describe the different "FROM"s.

  1. The return path (sometimes called the reverse path, envelope sender, or envelope from — all of these terms can be used interchangeably) is the value used in the SMTP session in the MAIL FROM command. As you can see, this does not need to be the same value that is found in the message headers. Only the recipient's mail server is supposed to add a Return-Path header to the top of the email. This records the actual Return-Path sender during the SMTP session. If a Return-Path header already exists in the message, then that header is removed and replaced by the recipient's mail server.

All bounces that occur during the SMTP session should go back to the Return-Path address. Some servers may accept all email, and then queue it locally, until it has a free thread to deliver it to the recipient's mailbox. If the recipient doesn't exist, it should bounce it back to the recorded Return-Path value.

Note, not all mail servers obey this rule; Some mail servers will bounce it back to the FROM address.

  1. The FROM address is the value found in the FROM header. This is supposed to be who the message is FROM. This is what you see as the "FROM" in most mail clients. If an email does not have a Reply-To header, then all human (mail client) replies should go back to the FROM address.

  2. The Reply-To header is added by the sender (or the sender's software). It is where all human replies should be addressed too. Basically, when the user clicks "reply", the Reply-To value should be the value used as the recipient of the newly composed email. The Reply-To value should not be used by any server. It is meant for client-side (MUA) use only.

However, as you can tell, not all mail servers obey the RFC standards or recommendations.

Hopefully this should help clear things up. However, if I missed anything, let me know, and I'll try to answer.

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

How to know if other threads have finished?

Here's a solution that is simple, short, easy to understand, and works perfectly for me. I needed to draw to the screen when another thread ends; but couldn't because the main thread has control of the screen. So:

(1) I created the global variable: boolean end1 = false; The thread sets it to true when ending. That is picked up in the mainthread by "postDelayed" loop, where it is responded to.

(2) My thread contains:

void myThread() {
    end1 = false;
    new CountDownTimer(((60000, 1000) { // milliseconds for onFinish, onTick
        public void onFinish()
        {
            // do stuff here once at end of time.
            end1 = true; // signal that the thread has ended.
        }
        public void onTick(long millisUntilFinished)
        {
          // do stuff here repeatedly.
        }
    }.start();

}

(3) Fortunately, "postDelayed" runs in the main thread, so that's where in check the other thread once each second. When the other thread ends, this can begin whatever we want to do next.

Handler h1 = new Handler();

private void checkThread() {
   h1.postDelayed(new Runnable() {
      public void run() {
         if (end1)
            // resond to the second thread ending here.
         else
            h1.postDelayed(this, 1000);
      }
   }, 1000);
}

(4) Finally, start the whole thing running somewhere in your code by calling:

void startThread()
{
   myThread();
   checkThread();
}

Webdriver and proxy server for firefox

FirefoxProfile profile = new FirefoxProfile();
String PROXY = "xx.xx.xx.xx:xx";
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);

It is for C#

How to catch a specific SqlException error?

For those of you rookies out there who may throw a SQL error when connecting to the DB from another machine(For example, at form load), you will find that when you first setup a datatable in C# which points to a SQL server database that it will setup a connection like this:

this.Table_nameTableAdapter.Fill(this.DatabaseNameDataSet.Table_name);

You may need to remove this line and replace it with something else like a traditional connection string as mentioned on MSDN, etc.

http://www.connectionstrings.com/sql-server-2008

How to view unallocated free space on a hard disk through terminal

when you cut you disk in partitions by fdisk you may be careful so as not to left gaps with free space. So command automatically align partitions and you'll get some gaps between parts. There are many articles in net why need to do so. The reason is that it gives solution with less errors. That was many years ago. Now I don't know is there errors occurs if you do all without any gaps. But first. You may do so if you don't allow alignment you sen begin of the next part=end previous+1. But is first part begins always with 2048 sector. So call expert part you may shift it to 0. But strongly recomended to do so if you plan to boot from this disk. If only for data you'll gain 1 Mb additional disk space. This is an MBR space. If you plan to install OS on this disk you don't use GPT partition type. Also it's more suitable not all OS see GPT parts of disks. But some see them. If you don't sure it use msdos. While format the block size is 4096 bytes(logical) physical one is 512 bytes. I don't do so but you may set block size=512 too. There was many discussion about that. It's lead to disk errors. But you'll give some free disk space too especially when you have many small size files. You disk will fill more compactly. And if you give already partitioned disk with filled them with data and maybe installed OS you maybe want to do so, it was very problems to do. But is possible for Linux. For Windows no... You must save backup and mbr too, write UUID every part then use fdisk and format as setting right UUID and LABEL for every part restore mbr with dd command and if you don't do any wrong all will be work as before but without any gaps.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Attempting to provide a concise update, based on Enzero's answer.

  • Install the Bootstrap.Datepicker package.

    PM> install-package Bootstrap.Datepicker
    ...
    Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
    
  • In AppStart/BundleConfig.cs, add the related scripts and styles in the bundles.

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
          //...,
          "~/Scripts/bootstrap-datepicker.js",
          "~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
          ...,
          "~/Content/bootstrap-datepicker3.css"));
    
  • In the related view, in the scripts' section, enable and customize datepicker.

    @section scripts{
        <script type="text/javascript">
            //...
            $('.datepicker').datepicker({
                format: 'dd/mm/yyyy', //choose the date format you prefer
                language: "YOUR-LOCALE-CODE-HERE",
                orientation: 'left bottom'
            });
        </script>
    
  • Eventually add the datepicker class in the related control. For instance, in a TextBox and for a date format in the like of "31/12/2018" this would be:

    @Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
    

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

JavaScript: What are .extend and .prototype used for?

  • .extends() create a class which is a child of another class.
    behind the scenes Child.prototype.__proto__ sets its value to Parent.prototype
    so methods are inherited.
  • .prototype inherit features from one to another.
  • .__proto__ is a getter/setter for Prototype.

Maven package/install without test (skip tests)

<properties>
    <maven.test.skip>true</maven.test.skip>
</properties>

is also a way to add in pom file

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Swift 3 / Alamofire 4.0 (Addendum to the accepted answer)

To append to multipartFormData in Swift 3 / Alamofire 4.0, use the following method of MultipartFormData:

public func append(_ data: Data, withName name: String) { /* ... */ }

And, to convert String to Data, the data(using:) method of String. E.g.,

multipartFormData.append("comment".data(using: .utf8)!, withName: "comment")

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.

Compare DATETIME and DATE ignoring time portion

You may use DateDiff and compare by day.

DateDiff(dd,@date1,@date2) > 0

It means @date2 > @date1

For example :

select DateDiff(dd, '01/01/2021 10:20:00', '02/01/2021 10:20:00') 

has the result : 1

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

MassAssignmentException in Laravel

User proper model in your controller file.

<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;

How to get the real and total length of char * (char array)?

Legit question. I personally think people confuse pointers with arrays as a result of character pointers (char*), which serve almost the same purpose as character arrays (char __[X]). This means that pointers and arrays are not the same, so pointers of course don't contain a specific size, only an address if I could say so. But nonetheless you can try something similar to strlen.

int ssize(const char* s)
{
    for (int i = 0; ; i++)
        if (s[i] == 0)
            return i;

    return 0;
}

Center text output from Graphics.DrawString()

Through a combination of the suggestions I got, I came up with this:

    private void DrawLetter()
    {
        Graphics g = this.CreateGraphics();

        float width = ((float)this.ClientRectangle.Width);
        float height = ((float)this.ClientRectangle.Width);

        float emSize = height;

        Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);

        font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);

        SizeF size = g.MeasureString(letter.ToString(), font);
        g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);

    }

    private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
    {
        // Compute actual size, shrink if needed
        while (true)
        {
            SizeF size = g.MeasureString(text, font);

            // It fits, back out
            if (size.Height <= proposedSize.Height &&
                 size.Width <= proposedSize.Width) { return font; }

            // Try a smaller font (90% of old size)
            Font oldFont = font;
            font = new Font(font.Name, (float)(font.Size * .9), font.Style);
            oldFont.Dispose();
        }
    }

So far, this works flawlessly.

The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness.

Deep cloning objects

A mapper performs a deep-copy. Foreach member of your object it creates a new object and assign all of its values. It works recursively on each non-primitive inner member.

I suggest you one of the fastest, currently actively developed ones. I suggest UltraMapper https://github.com/maurosampietro/UltraMapper

Nuget packages: https://www.nuget.org/packages/UltraMapper/

Using wget to recursively fetch a directory with arbitrary files in it

Here's the complete wget command that worked for me to download files from a server's directory (ignoring robots.txt):

wget -e robots=off --cut-dirs=3 --user-agent=Mozilla/5.0 --reject="index.html*" --no-parent --recursive --relative --level=1 --no-directories http://www.example.com/archive/example/5.3.0/

How to set bootstrap navbar active class with Angular JS?

You can actually use angular-ui-utils' ui-route directive:

<a ui-route ng-href="/">Home</a>
<a ui-route ng-href="/about">About</a>
<a ui-route ng-href="/contact">Contact</a>

or:

Header Controller

/**
 * Header controller
 */
angular.module('myApp')
  .controller('HeaderCtrl', function ($scope) {
    $scope.menuItems = [
      {
        name: 'Home',
        url:  '/',
        title: 'Go to homepage.'
      },
      {
        name:   'About',
        url:    '/about',
        title:  'Learn about the project.'
      },
      {
        name:   'Contact',
        url:    '/contact',
        title:  'Contact us.'
      }
    ];
  });

Index page

<!-- index.html: -->
<div class="header" ng-controller="HeaderCtrl">
  <ul class="nav navbar-nav navbar-right">
    <li ui-route="{{menuItem.url}}" ng-class="{active: $uiRoute}"
      ng-repeat="menuItem in menuItems">
      <a ng-href="#{{menuItem.url}}" title="{{menuItem.title}}">
        {{menuItem.name}}
      </a>
    </li>
  </ul>
</div>

If you're using ui-utils, you may also be interested in ui-router for managing partial/nested views.

Open new popup window without address bars in firefox & IE

I know this is a very old question, yes, I agree we can not hide address bar in modern browsers, but we can hide the url in address bar (e.g show url about:blank), following is my work around solution.

var iframe = '<html><head><style>body, html {width: 100%; height: 100%; margin: 0; padding: 0}</style></head><body><iframe src="https://www.w3schools.com" style="height:calc(100% - 4px);width:calc(100% - 4px)"></iframe></html></body>';

var win = window.open("","","width=600,height=480,toolbar=no,menubar=no,resizable=yes");
win.document.write(iframe);

is it possible to add colors to python output?

IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.

You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle documentation just tells you the basics of using IDLE itself, and its idlelib library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.


Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)

Learning to read the termcap entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.

Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.

But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.

Apk location in New Android Studio

For Gradle look here: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.SourceSetOutput.html. "For example: Java plugin will use those dirs in calculating class paths and for jarring the content; IDEA and Eclipse plugins will put those folders on relevant classpath."

So its depend on plugin build in configs unless you don't define them explicit in config file.

How to check if the URL contains a given string?

I like to create a boolean and then use that in a logical if.

//kick unvalidated users to the login page
var onLoginPage = (window.location.href.indexOf("login") > -1);

if (!onLoginPage) {
  console.log('redirected to login page');
  window.location = "/login";
} else {
  console.log('already on the login page');
}

How to use Sublime over SSH

You can use sftp to mount the remote directory on your location machine and then simply open the files using Sublime text the way you normally would.

To mount remote directory using sftp, enter the following on your Linux file manager;

sftp://user@remote_box.com:22/home/user/code_directory

It might seem slow depending on your internet speeds. But this worked for me.

How to get the insert ID in JDBC?

It is possible to use it with normal Statement's as well (not just PreparedStatement)

Statement statement = conn.createStatement();
int updateCount = statement.executeUpdate("insert into x...)", Statement.RETURN_GENERATED_KEYS);
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
  if (generatedKeys.next()) {
    return generatedKeys.getLong(1);
  }
  else {
    throw new SQLException("Creating failed, no ID obtained.");
  }
}

Ternary operation in CoffeeScript

a = if true then 5 else 10
a = if false then 5 else 10 

See documentation.

Get Current date in epoch from Unix shell script

Depending on the language you're using it's going to be something simple like

CInt(CDate("1970-1-1") - CDate(Today()))

Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.

Setting Authorization Header of HttpClient

this could works, if you are receiving a json or an xml from the service and i think this can give you an idea about how the headers and the T type works too, if you use the function MakeXmlRequest(put results in xmldocumnet) and MakeJsonRequest(put the json in the class you wish that have the same structure that the json response) in the next way

/*-------------------------example of use-------------*/
MakeXmlRequest<XmlDocument>("your_uri",result=>your_xmlDocument_variable =     result,error=>your_exception_Var = error);

MakeJsonRequest<classwhateveryouwant>("your_uri",result=>your_classwhateveryouwant_variable=result,error=>your_exception_Var=error)
/*-------------------------------------------------------------------------------*/


public class RestService
{
    public void MakeXmlRequest<T>(string uri, Action<XmlDocument> successAction, Action<Exception> errorAction)
    {
        XmlDocument XMLResponse = new XmlDocument();
        string wufooAPIKey = ""; /*or username as well*/
        string password = "";
        StringBuilder url = new StringBuilder();
        url.Append(uri);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
        string authInfo = wufooAPIKey + ":" + password;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Timeout = 30000;
        request.KeepAlive = false;
        request.Headers["Authorization"] = "Basic " + authInfo;
        string documento = "";
        MakeRequest(request,response=> documento = response,
                            (error) =>
                            {
                             if (errorAction != null)
                             {
                                errorAction(error);
                             }
                            }
                   );
        XMLResponse.LoadXml(documento);
        successAction(XMLResponse);
    }



    public void MakeJsonRequest<T>(string uri, Action<T> successAction, Action<Exception> errorAction)
    {
        string wufooAPIKey = "";
        string password = "";
        StringBuilder url = new StringBuilder();
        url.Append(uri);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
        string authInfo = wufooAPIKey + ":" + password;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        request.Timeout = 30000;
        request.KeepAlive = false;
        request.Headers["Authorization"] = "Basic " + authInfo;
       // request.Accept = "application/json";
      //  request.Method = "GET";
        MakeRequest(
           request,
           (response) =>
           {
               if (successAction != null)
               {
                   T toReturn;
                   try
                   {
                       toReturn = Deserialize<T>(response);
                   }
                   catch (Exception ex)
                   {
                       errorAction(ex);
                       return;
                   }
                   successAction(toReturn);
               }
           },
           (error) =>
           {
               if (errorAction != null)
               {
                   errorAction(error);
               }
           }
        );
    }
    private void MakeRequest(HttpWebRequest request, Action<string> successAction, Action<Exception> errorAction)
    {
        try{
            using (var webResponse = (HttpWebResponse)request.GetResponse())
            {
                using (var reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    var objText = reader.ReadToEnd();
                    successAction(objText);
                }
            }
        }catch(HttpException ex){
            errorAction(ex);
        }
    }
    private T Deserialize<T>(string responseBody)
    {
        try
        {
            var toReturns = JsonConvert.DeserializeObject<T>(responseBody);
             return toReturns;
        }
        catch (Exception ex)
        {
            string errores;
            errores = ex.Message;
        }
        var toReturn = JsonConvert.DeserializeObject<T>(responseBody);
        return toReturn;
    }
}
}

How do I create delegates in Objective-C?

Here is a simple method to create delegates

Create Protocol in .h file. Make sure that is defined before the protocol using @class followed by the name of the UIViewController < As the protocol I am going to use is UIViewController class>.

Step : 1 : Create a new class Protocol named "YourViewController" which will be the subclass of UIViewController class and assign this class to the second ViewController.

Step : 2 : Go to the "YourViewController" file and modify it as below:

#import <UIKit/UIkit.h>
@class YourViewController;

@protocol YourViewController Delegate <NSObject>

 @optional
-(void)defineDelegateMethodName: (YourViewController *) controller;

@required
-(BOOL)delegateMethodReturningBool: (YourViewController *) controller;

  @end
  @interface YourViewController : UIViewController

  //Since the property for the protocol could be of any class, then it will be marked as a type of id.

  @property (nonatomic, weak) id< YourViewController Delegate> delegate;

@end

The methods defined in the protocol behavior can be controlled with @optional and @required as part of the protocol definition.

Step : 3 : Implementation of Delegate

    #import "delegate.h"

   @interface YourDelegateUser ()
     <YourViewControllerDelegate>
   @end

   @implementation YourDelegateUser

   - (void) variousFoo {
      YourViewController *controller = [[YourViewController alloc] init];
      controller.delegate = self;
   }

   -(void)defineDelegateMethodName: (YourViewController *) controller {
      // handle the delegate being called here
   }

   -(BOOL)delegateMethodReturningBool: (YourViewController *) controller {
      // handle the delegate being called here
      return YES;
   }

   @end

//test whether the method has been defined before you call it

 - (void) someMethodToCallDelegate {
     if ([[self delegate] respondsToSelector:@selector(defineDelegateMethodName:)]) {
           [self.delegate delegateMethodName:self]; 
     }
  }

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

How do I split a string in Rust?

There are three simple ways:

  1. By separator:

     s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
    
  2. By whitespace:

     s.split_whitespace()
    
  3. By newlines:

     s.lines()
    
  4. By regex: (using regex crate)

     Regex::new(r"\s").unwrap().split("one two three")
    

The result of each kind is an iterator:

let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());

What does the 'L' in front a string mean in C++?

It's a wchar_t literal, for extended character set. Wikipedia has a little discussion on this topic, and c++ examples.

How to make a phone call in android and come back to my activity when the call is done?

This is solution from my point of view:

ok.setOnClickListener(this);
@Override
public void onClick(View view) {
    if(view == ok){
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + num));
        activity.startActivity(intent);

    }

Of course in Activity (class) definition you have to implement View.OnClickListener .

Java 8 optional: ifPresent return object orElseThrow exception

Two options here:

Replace ifPresent with map and use Function instead of Consumer

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object
            .map(obj -> {
                String result = "result";
                //some logic with result and return it
                return result;
            })
            .orElseThrow(MyCustomException::new);
}

Use isPresent:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    if (object.isPresent()) {
        String result = "result";
        //some logic with result and return it
        return result;
    } else {
        throw new MyCustomException();
    }
}

How can I use a carriage return in a HTML tooltip?

Just use JavaScript. Then compatible with most and older browsers. Use the escape sequence \n for newline.

   document.getElementById("ElementID").title = 'First Line text \n Second line text'

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

As smnbss comments in Darin Dimitrov's answer, Prompt exists for exactly this purpose, so there is no need to create a custom attribute. From the the documentation:

Gets or sets a value that will be used to set the watermark for prompts in the UI.

To use it, just decorate your view model's property like so:

[Display(Prompt = "numbers only")]
public int Age { get; set; }

This text is then conveniently placed in ModelMetadata.Watermark. Out of the box, the default template in MVC 3 ignores the Watermark property, but making it work is really simple. All you need to do is tweaking the default string template, to tell MVC how to render it. Just edit String.cshtml, like Darin does, except that rather than getting the watermark from ModelMetadata.AdditionalValues, you get it straight from ModelMetadata.Watermark:

~/Views/Shared/EditorTemplates/String.cshtml:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })

And that is it.

As you can see, the key to make everything work is the placeholder = ViewData.ModelMetadata.Watermark bit.

If you also want to enable watermarking for multi-line textboxes (textareas), you do the same for MultilineText.cshtml:

~/Views/Shared/EditorTemplates/MultilineText.cshtml:

@Html.TextArea("", ViewData.TemplateInfo.FormattedModelValue.ToString(), 0, 0, new { @class = "text-box multi-line", placeholder = ViewData.ModelMetadata.Watermark })

How to perform element-wise multiplication of two lists?

create an array of ones; multiply each list times the array; convert array to a list

import numpy as np

a = [1,2,3,4]
b = [2,3,4,5]

c = (np.ones(len(a))*a*b).tolist()

[2.0, 6.0, 12.0, 20.0]

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You can, if uploading an entire folder is an option for you

<input type="file" webkitdirectory directory multiple/>

change event will contain:

.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"

The simplest possible JavaScript countdown timer?

You can easily create a timer functionality by using setInterval.Below is the code which you can use it to create the timer.

http://jsfiddle.net/ayyadurai/GXzhZ/1/

_x000D_
_x000D_
window.onload = function() {_x000D_
  var minute = 5;_x000D_
  var sec = 60;_x000D_
  setInterval(function() {_x000D_
    document.getElementById("timer").innerHTML = minute + " : " + sec;_x000D_
    sec--;_x000D_
    if (sec == 00) {_x000D_
      minute --;_x000D_
      sec = 60;_x000D_
      if (minute == 0) {_x000D_
        minute = 5;_x000D_
      }_x000D_
    }_x000D_
  }, 1000);_x000D_
}
_x000D_
Registration closes in <span id="timer">05:00<span> minutes!
_x000D_
_x000D_
_x000D_

Get item in the list in Scala?

Why parentheses?

Here is the quote from the book programming in scala.

Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.

Here are a few examples how to pull certain element (first elem in this case) using functional programming style.

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)

How to remove numbers from string using Regex.Replace?

the best design is:

public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

How to fetch Java version using single line command in Linux

  1. Redirect stderr to stdout.
  2. Get first line
  3. Filter the version number.

    java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
    

Python AttributeError: 'module' object has no attribute 'Serial'

If you are helpless like me, try this:

List all Sub-Modules of "Serial" (or whatever package you are having trouble with) with the method described here: List all the modules that are part of a python package

In my case, the problems solved one after the other.

...looks like a bug to me...

Convert a double to a QString

You can use arg(), as follow:

double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);

This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision

How to match all occurrences of a regex

Using scan should do the trick:

string.scan(/regex/)

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Combining all conditions

select  a.* from tbl_Company a

where  a.Company_ID NOT IN (1,2)  

AND (   
        (0 = 
            CASE WHEN (@Fromdate = '' or @Todate='')
                THEN 0 
                ELSE 1  
            END
        )      -- if 0=0 true , if 0=1 fails (filter only when the fromdate and todate is present)
                OR
        (a.Created_Date between @Fromdate and @Todate )                 
    )

How do I set the background color of my main screen in Flutter?

Here's one way that I found to do it. I don't know if there are better ways, or what the trade-offs are.

Container "tries to be as big as possible", according to https://flutter.io/layout/. Also, Container can take a decoration, which can be a BoxDecoration, which can have a color (which, is the background color).

Here's a sample that does indeed fill the screen with red, and puts "Hello, World!" into the center:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new Container(
      decoration: new BoxDecoration(color: Colors.red),
      child: new Center(
        child: new Text("Hello, World!"),
      ),
    );
  }
}

Note, the Container is returned by the MyApp build(). The Container has a decoration and a child, which is the centered text.

See it in action here:

enter image description here

How to change the value of attribute in appSettings section with Web.config transformation

You want something like:

<appSettings>
  <add key="developmentModeUserId" xdt:Transform="Remove" xdt:Locator="Match(key)"/>
  <add key="developmentMode" value="false" xdt:Transform="SetAttributes"
          xdt:Locator="Match(key)"/>
</appSettings>

See Also: Web.config Transformation Syntax for Web Application Project Deployment

jQuery attr('onclick')

The easyest way is to change .attr() function to a javascript function .setAttribute()

$('#stop').click(function() {
    $('next')[0].setAttribute('onclick','stopMoving()');
}

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Finding the type of an object in C++

Use overloaded functions. Does not require dynamic_cast or even RTTI support:

class A {};
class B : public A {};

class Foo {
public:
    void Bar(A& a) {
        // do something
    }
    void Bar(B& b) {
        Bar(static_cast<A&>(b));
        // do B specific stuff
    }
};

Failed to resolve: com.android.support:appcompat-v7:26.0.0

My issue got resolved with the help of following steps:

For gradle 3.0.0 and above version

  1. add google() below jcenter()
  2. Change the compileSdkVersion to 26 and buildToolsVersion to 26.0.2
  3. Change to gradle-4.2.1-all.zip in the gradle_wrapper.properties file