Programs & Examples On #Fantom

Fantom is designed as a practical programming language to make it easy and fun to get real work done. It is not an academic language to explore bleeding edge theories, but based on solid real world experience. During its design we set out to solve what we perceived were some real problems with Java and C#. Our background is heavily Java, but many of Java's problems are shared by C# and .NET also.

Git command to checkout any branch and overwrite local changes

Couple of points:

  • I believe git stash + git stash drop could be replaced with git reset --hard
  • ... or, even shorter, add -f to checkout command:

    git checkout -f -b $branch
    

    That will discard any local changes, just as if git reset --hard was used prior to checkout.

As for the main question: instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.

Asp Net Web API 2.1 get client IP address

string userRequest = System.Web.HttpContext.Current.Request.UserHostAddress;

This works on me.

System.Web.HttpContext.Current.Request.UserHostName; this one return me the same return I get from the UserHostAddress.

Correct way to write loops for promise.

Using the standard promise object, and having the promise return the results.

function promiseMap (data, f) {
  const reducer = (promise, x) =>
    promise.then(acc => f(x).then(y => acc.push(y) && acc))
  return data.reduce(reducer, Promise.resolve([]))
}

var emails = []

function getUser(email) {
  return db.getUser(email)
}

promiseMap(emails, getUser).then(emails => {
  console.log(emails)
})

How to pass json POST data to Web API method as an object?

1)In your client side you can send you http.post request in string like below

var IndexInfo = JSON.stringify(this.scope.IndexTree);
this.$http.post('../../../api/EvaluationProcess/InsertEvaluationProcessInputType', "'" + IndexInfo + "'" ).then((response: any) => {}

2)Then in your web api controller you can deserialize it

public ApiResponce InsertEvaluationProcessInputType([FromBody]string IndexInfo)
    {
var des = (ApiReceivedListOfObjects<TempDistributedIndex>)Newtonsoft.Json.JsonConvert.DeserializeObject(DecryptedProcessInfo, typeof(ApiReceivedListOfObjects<TempDistributedIndex>));}

3)Your ApiReceivedListOfObjects class should be like below

public class ApiReceivedListOfObjects<T>
    {
        public List<T> element { get; set; }

    }

4)make sure that your serialized string (IndexInfo here) becomes like below structure before JsonConvert.DeserializeObject command in step 2

var resp = @"
    {
        ""element"": [
        {
            ""A"": ""A Jones"",
            ""B"": ""500015763""
        },
        {
            ""A"": ""B Smith"",
            ""B"": ""504986213""
        },
        {
            ""A"": ""C Brown"",
            ""B"": ""509034361""
        }
        ]
    }";

Creating a div element in jQuery

All these worked for me,

HTML part:

<div id="targetDIV" style="border: 1px solid Red">
    This text is surrounded by a DIV tag whose id is "targetDIV".
</div>

JavaScript code:

//Way 1: appendTo()
<script type="text/javascript">
    $("<div>hello stackoverflow users</div>").appendTo("#targetDIV"); //appendTo: Append at inside bottom
</script>

//Way 2: prependTo()
<script type="text/javascript">
    $("<div>Hello, Stack Overflow users</div>").prependTo("#targetDIV"); //prependTo: Append at inside top
</script>

//Way 3: html()
<script type="text/javascript">
    $("#targetDIV").html("<div>Hello, Stack Overflow users</div>"); //.html(): Clean HTML inside and append
</script>

//Way 4: append()
<script type="text/javascript">
    $("#targetDIV").append("<div>Hello, Stack Overflow users</div>"); //Same as appendTo
</script>

SQL/mysql - Select distinct/UNIQUE but return all columns?

You can do it with a WITH clause.

For example:

WITH c AS (SELECT DISTINCT a, b, c FROM tableName)
SELECT * FROM tableName r, c WHERE c.rowid=r.rowid AND c.a=r.a AND c.b=r.b AND c.c=r.c

This also allows you to select only the rows selected in the WITH clauses query.

How to express a NOT IN query with ActiveRecord/Rails?

When you query a blank array add "<< 0" to the array in the where block so it doesn't return "NULL" and break the query.

Topic.where('id not in (?)',actions << 0)

If actions could be an empty or blank array.

SQLite UPSERT / UPDATE OR INSERT

To have a pure UPSERT with no holes (for programmers) that don't relay on unique and other keys:

UPDATE players SET user_name="gil", age=32 WHERE user_name='george'; 
SELECT changes();

SELECT changes() will return the number of updates done in the last inquire. Then check if return value from changes() is 0, if so execute:

INSERT INTO players (user_name, age) VALUES ('gil', 32); 

Fully change package name including company domain

current package : com.company.name

New package : com.mycomapny.name

Steps: 1) Suppose you are at this screen which is shown below.

enter image description here

2) Open project pane and click on settings icon.

3) Deselect Compact Empty Middle Packages.

4) Then your package is now broken into individual parts as shown below .

5) right click on "company" select Refactor -> select rename ->rename directory.

enter image description here

6) Now your "company" has been changed to new "mycomapny" and changes were reflected as shown in below figure.

enter image description here

7) Now change the package name in AndroidManifest.xml file .

enter image description here

8) Open app level build.gradle and change package name .

enter image description here

9) you will get errors as Cannot resolve symbol "R" .

10) Remove line which gives this error and studio will import new R file automatically.

11) If you have multiple files then use find and replace option by pressing " Cntrl+Shift+R "

Or " Select Edit->Find->Replace in path.."

enter image description here

12) select Replace All.

Spin or rotate an image on hover

It's very simple.

  1. You add an image.
  2. You create a css property to this image.

    img { transition: all 0.3s ease-in-out 0s; }
    
  3. You add an animation like that:

    img:hover
    {
        cursor: default;
        transform: rotate(360deg);
        transition: all 0.3s ease-in-out 0s;
    }
    

Convert named list to vector with values only

This can be done by using unlist before as.vector. The result is the same as using the parameter use.names=FALSE.

as.vector(unlist(myList))

Recover unsaved SQL query scripts

I use the free file searching program Everything, search for *.sql files across my C: drive, and then sort by Last Modified, and then browse by the date I think it was probably last executed.

It usually brings up loads of autorecovery files from a variety of locations. And you don't have to worry where the latest version of SSMS/VS is saving the backup files this version.

enter image description here

Javascript to stop HTML5 video playback on modal window close

I managed to stop the video using "get(0)" (Retrieve the DOM elements matched by the jQuery object):

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer").get(0).pause();
    return false;
});

Oracle - What TNS Names file am I using?

The easiest way is probably to check the PATH environment variable of the process that is connecting to the database. Most likely the tnsnames.ora file is in first Oracle bin directory in path..\network\admin. TNS_ADMIN environment variable or value in registry (for the current Oracle home) may override this.

Using filemon like suggested by others will also do the trick.

MySQL the right syntax to use near '' at line 1 error

INSERT INTO wp_bp_activity
            (
            user_id,
             component,
             `type`,
             `action`,
             content,
             primary_link,
             item_id,
             secondary_item_id,
             date_recorded,
             hide_sitewide,
             mptt_left,
             mptt_right
             )
             VALUES(
             1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
             )

In Angular, how to add Validator to FormControl after control is created?

To add onto what @Delosdos has posted.

Set a validator for a control in the FormGroup: this.myForm.controls['controlName'].setValidators([Validators.required])

Remove the validator from the control in the FormGroup: this.myForm.controls['controlName'].clearValidators()

Update the FormGroup once you have run either of the above lines. this.myForm.controls['controlName'].updateValueAndValidity()

This is an amazing way to programmatically set your form validation.

Why the switch statement cannot be applied on strings?

To add a variation using the simplest container possible (no need for an ordered map)... I wouldn't bother with an enum--just put the container definition immediately before the switch so it'll be easy to see which number represents which case.

This does a hashed lookup in the unordered_map and uses the associated int to drive the switch statement. Should be quite fast. Note that at is used instead of [], as I've made that container const. Using [] can be dangerous--if the string isn't in the map, you'll create a new mapping and may end up with undefined results or a continuously growing map.

Note that the at() function will throw an exception if the string isn't in the map. So you may want to test first using count().

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
switch(string_to_case.at("raj")) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;


}

The version with a test for an undefined string follows:

const static std::unordered_map<std::string,int> string_to_case{
   {"raj",1},
   {"ben",2}
};
// in C++20, you can replace .count with .contains
switch(string_to_case.count("raj") ? string_to_case.at("raj") : 0) {
  case 1: // this is the "raj" case
       break;
  case 2: // this is the "ben" case
       break;
  case 0: //this is for the undefined case

}

javascript : sending custom parameters with window.open() but its not working

if you want to pass POST variables, you have to use a HTML Form:

<form action="http://localhost:8080/login" method="POST" target="_blank">
    <input type="text" name="cid" />
    <input type="password" name="pwd" />
    <input type="submit" value="open" />
</form>

or:

if you want to pass GET variables in an URL, write them without single-quotes:

http://yourdomain.com/login?cid=username&pwd=password

here's how to create the string above with javascrpt variables:

myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");

in the document with that url, you have to read the GET parameters. if it's in php, use:

$_GET['username']

be aware: to transmit passwords that way is a big security leak!

Is there a method to generate a UUID with go language

The go-uuid library is NOT RFC4122 compliant. The variant bits are not set correctly. There have been several attempts by community members to have this fixed but pull requests for the fix are not being accepted.

You can generate UUIDs using the Go uuid library I rewrote based on the go-uuid library. There are several fixes and improvements. This can be installed with:

go get github.com/twinj/uuid

You can generate random (version 4) UUIDs with:

import "github.com/twinj/uuid"

u := uuid.NewV4()

The returned UUID type is an interface and the underlying type is an array.

The library also generates v1 UUIDs and correctly generates v3 and 5 UUIDs. There are several new methods to help with printing and formatting and also new general methods to create UUIDs based off of existing data.

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

PHP doesn't really get compiled as with many programs. You can use Zend's encoder to make it unreadable though.

How to install XCODE in windows 7 platform?

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

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

Source: classroomm.com

Generate a sequence of numbers in Python

Assuming I've guessed the pattern correctly (alternating increments of 1 and 3), this should produce the desired result:

def sequence():
    res = []
    diff = 1
    x = 1
    while x <= 100:
        res.append(x)
        x += diff
        diff = 3 if diff == 1 else 1
    return ', '.join(res)

Removing the remembered login and password list in SQL Server Management Studio

Delete:

C:\Documents and Settings\%Your Username%\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat"

Hello World in Python

In python 3.x. you use

print("Hello, World")

In Python 2.x. you use

print "Hello, World!"

How to check if the docker engine and a docker container are running?

You can check with this command systemctl status docker it will show the status of the docker. If you want to start you can use systemctl start docker instead of systemctl you can try also with service, service docker status and service docker start respectively.

Read a XML (from a string) and get some fields - Problems reading XML

Or use the XmlSerializer class.

XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));

How to get the exact local time of client?

my code is

  <html>
  <head>
  <title>Title</title>
  <script type="text/javascript"> 
  function display_c(){
  var refresh=1000; // Refresh rate in milli seconds
  mytime=setTimeout('display_ct()',refresh)
  }

  function display_ct() {
  var strcount
  var x = new Date()
  document.getElementById('ct').innerHTML = x;
  tt=display_c();
  }
  </script>
  </head>

  <body onload=display_ct();>
  <span id='ct' ></span>

  </body>
  </html>

if you want more codes visit my blog http://mysimplejavascriptcode.blogspot.in/

Matrix Multiplication in pure Python?

If you really don't want to use numpy you can do something like this:

def matmult(a,b):
    zip_b = zip(*b)
    # uncomment next line if python 3 : 
    # zip_b = list(zip_b)
    return [[sum(ele_a*ele_b for ele_a, ele_b in zip(row_a, col_b)) 
             for col_b in zip_b] for row_a in a]

x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
y = [[1,2],[1,2],[3,4]]

import numpy as np # I want to check my solution with numpy

mx = np.matrix(x)
my = np.matrix(y)       

Result:

>>> matmult(x,y)
[[12, 18], [27, 42], [42, 66], [57, 90]]
>>> mx * my
matrix([[12, 18],
        [27, 42],
        [42, 66],
        [57, 90]])

How do I select a MySQL database through CLI?

Alternatively, you can give the "full location" to the database in your queries a la:

SELECT photo_id FROM [my database name].photogallery;

If using one more often than others, use USE. Even if you do, you can still use the database.table syntax.

strcpy() error in Visual studio 2012

The message you are getting is advice from MS that they recommend that you do not use the standard strcpy function. Their motivation in this is that it is easy to misuse in bad ways (and the compiler generally can't detect and warn you about such misuse). In your post, you are doing exactly that. You can get rid of the message by telling the compiler to not give you that advice. The serious error in your code would remain, however.

You are creating a buffer with room for 10 chars. You are then stuffing 11 chars into it. (Remember the terminating '\0'?) You have taken a box with exactly enough room for 10 eggs and tried to jam 11 eggs into it. What does that get you? Not doing this is your responsibility and the compiler will generally not detect such things.

You have tagged this C++ and included string. I do not know your motivation for using strcpy, but if you use std::string instead of C style strings, you will get boxes that expand to accommodate what you stuff in them.

Launch Minecraft from command line - username and password as prefix

You can do this, you just need to circumvent the launcher.

In %appdata%\.minecraft\bin (or ~/.minecraft/bin on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.

Invoke it like so:

java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>

Set the working directory to .minecraft/bin.

To get the session ID, POST (request this page):

https://login.minecraft.net?user=<username>&password=<password>&version=13

You'll get a response like this:

1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98

The fourth field is the session ID. More details here. Read those details, this answer is outdated

Here's an example of logging in to minecraft.net in C#.

Get Environment Variable from Docker Container

You can use printenv VARIABLE instead of /bin/bash -c 'echo $VARIABLE. It's much simpler and it does not perform substitution:

docker exec container printenv VARIABLE

What character represents a new line in a text area

It seems that, according to the HTML5 spec, the value property of the textarea element should return '\r\n' for a newline:

The element's value is defined to be the element's raw value with the following transformation applied:

Replace every occurrence of a "CR" (U+000D) character not followed by a "LF" (U+000A) character, and every occurrence of a "LF" (U+000A) character not preceded by a "CR" (U+000D) character, by a two-character string consisting of a U+000D CARRIAGE RETURN "CRLF" (U+000A) character pair.

Following the link to 'value' makes it clear that it refers to the value property accessed in javascript:

Form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

However, in all five major browsers (using Windows, 11/27/2015), if '\r\n' is written to a textarea, the '\r' is stripped. (To test: var e=document.createElement('textarea'); e.value='\r\n'; alert(e.value=='\n');) This is true of IE since v9. Before that, IE was returning '\r\n' and converting both '\r' and '\n' to '\r\n' (which is the HTML5 spec). So... I'm confused.

To be safe, it's usually enough to use '\r?\n' in regular expressions instead of just '\n', but if the newline sequence must be known, a test like the above can be performed in the app.

Alternative to a goto statement in Java

While some commenters and downvoters argue that this isn't goto, the generated bytecode from the below Java statements really suggests that these statements really do express goto semantics.

Specifically, the do {...} while(true); loop in the second example is optimised by Java compilers in order not to evaluate the loop condition.

Jumping forward

label: {
  // do stuff
  if (check) break label;
  // do more stuff
}

In bytecode:

2  iload_1 [check]
3  ifeq 6          // Jumping forward
6  ..

Jumping backward

label: do {
  // do stuff
  if (check) continue label;
  // do more stuff
  break label;
} while(true);

In bytecode:

 2  iload_1 [check]
 3  ifeq 9
 6  goto 2          // Jumping backward
 9  ..

T-SQL: Selecting rows to delete via joins

DELETE TableA
FROM   TableA a
       INNER JOIN TableB b
               ON b.Bid = a.Bid
                  AND [my filter condition] 

should work

Tooltips with Twitter Bootstrap

I included the JS and CSS file and was wondering why it is not working, what made it work was when I added the following in <head>:

<script>
jQuery(function ($) {
    $("a").tooltip()
});
</script>

How to change default format at created_at and updated_at value laravel

Laravel 4.x and 5.0

To change the time in the database use: http://laravel.com/docs/4.2/eloquent#timestamps

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

class User extends Eloquent {

    protected function getDateFormat()
    {
        return 'U';
    }

}

Laravel 5.1+

https://laravel.com/docs/5.1/eloquent

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

class Flight extends Model
{
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
}

How to simulate a button click using code?

Starting with API15, you can use also callOnClick() that directly call attached view OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.

The developers of this app have not set up this app properly for Facebook Login?

For other users that run into this issue, the app I was testing against was a test version of our production app and didn't have the option to turn status and review to ON as others have mentioned here.

The fix was to create a new app which is not a test app, and configure it like the production version. The non-test version allows the option to turn status and review to ON.

My specific use was testing a user registered with a phone number instead of an email address. I tried adding that user into different roles of our test app (Developer and Tester), but to no avail. My guess is it has something to do with the user not having an email associated with it.

Here's more info on test apps: https://developers.facebook.com/docs/apps/test-apps

R adding days to a date

Use +

> as.Date("2001-01-01") + 45
[1] "2001-02-15"

Pip install Matplotlib error with virtualenv

To generate graph in png format you need to Install following dependent packages

sudo apt-get install libpng-dev
sudo apt-get install libfreetype6-dev

Ubuntu https://apps.ubuntu.com/cat/applications/libpng12-0/ or using following command

sudo apt-get install libpng12-0

Counting Number of Letters in a string variable

string yourWord = "Derp derp";

Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray()));

Yields:

____ ____

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

As an addendum to akf's answer you could use instanceof checks instead of String equals() calls:

String cname="com.some.vendor.Impl";
try {
  Class c=this.getClass().getClassLoader().loadClass(cname);
  Object o= c.newInstance();
  if(o instanceof Spam) {
    Spam spam=(Spam) o;
    process(spam);
  }
  else if(o instanceof Ham) {
    Ham ham = (Ham) o;
    process(ham);
  }
  /* etcetera */
}
catch(SecurityException se) {
  System.err.printf("Someone trying to game the system?%nOr a rename is in order because this JVM doesn't feel comfortable with: “%s”", cname);
  se.printStackTrace();
}
catch(LinkageError le) {
  System.err.printf("Seems like a bad class to this JVM: “%s”.", cname);
  le.printStackTrace();
}
catch(RuntimeException re) { 
  // runtime exceptions I might have forgotten. Classloaders are wont to produce those.
  re.printStackTrace();
}
catch(Exception e) { 
  e.printStackTrace();
}

Note the liberal hardcoding of some values. Anyways the main points are:

  1. Use instanceof rather than equals(). If anything, it will co-operate better when refactoring.
  2. Be sure to catch these runtime errors and security ones too.

How to completely remove a dialog on close

An ugly solution that works like a charm for me:

$("#mydialog").dialog(
    open: function(){
        $('div.ui-widget-overlay').hide();
        $("div.ui-dialog").not(':first').remove();
}
});

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

How to set TextView textStyle such as bold, italic

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

To keep the previous typeface

textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)

How do I add a .click() event to an image?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
<script type="text/javascript" src="jquery-2.1.0.js"></script> 
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
 var img = document.createElement('img');
 img.setAttribute('src', 'tiger.jpg');
  img.setAttribute('width', '200');
   img.setAttribute('height', '150');
  document.getElementById("images").appendChild(img);


}


</script>
</head>
<body>

<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>

<div id="images" >
</div>

<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />

</body>
</html> 

How can I pass arguments to anonymous functions in JavaScript?

By removing the parameter from the anonymous function will be available in the body.

    myButton.onclick = function() { alert(myMessage); };

For more info search for 'javascript closures'

How to create a data file for gnuplot?

I was having the exact same issue. The problem that I was having is that I hadn't saved the .plt file that I was typing into yet. The fix: I saved the .plt file in the same directory as the data that I was trying to plot and suddenly it worked! If they are in the same directory, you don't even need to specify a path, you can just put in the file name.

Below is exactly what was happening to me, and how I fixed it. The first line shows the problem we were both having. I saved in the second line, and the third line worked!

gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'
         warning: Skipping unreadable file c:/Documents and Settings/User/Desktop/data.dat
         No data in plot

gnuplot> save 'c:/Documents and Settings/User/Desktop/myfile.plt'

gnuplot> plot 'c:/Documents and Settings/User/Desktop/data.dat'

How might I extract the property values of a JavaScript object into an array?

Maybe a bit verbose, but robust and fast

var result = [];
var keys = Object.keys(myObject);
for (var i = 0, len = keys.length; i < len; i++) {
    result.push(myObject[keys[i]]);
}

Express.js req.body undefined

Express 4, has build-in body parser. No need to install separate body-parser. So below will work:

export const app = express();
app.use(express.json());

Comparing two dictionaries and checking how many (key, value) pairs are equal

Why not just iterate through one dictionary and check the other in the process (assuming both dictionaries have the same keys)?

x = dict(a=1, b=2)
y = dict(a=2, b=2)

for key, val in x.items():
    if val == y[key]:
        print ('Ok', val, y[key])
    else:
        print ('Not', val, y[key])

Output:

Not 1 2
Ok 2 2

Docker: Multiple Dockerfiles in project

Use docker-compose and multiple Dockerfile in separate directories

Don't rename your Dockerfile to Dockerfile.db or Dockerfile.web, it may not be supported by your IDE and you will lose syntax highlighting.

As Kingsley Uchnor said, you can have multiple Dockerfile, one per directory, which represent something you want to build.

I like to have a docker folder which holds each applications and their configuration. Here's an example project folder hierarchy for a web application that has a database.

docker-compose.yml
docker
+-- web
¦   +-- Dockerfile
+-- db
    +-- Dockerfile

docker-compose.yml example:

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: ./docker/web
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  db:
    # will build ./docker/db/Dockerfile
    build: ./docker/db
    ports:
      - "3306:3306"
  redis:
    # will use docker hub's redis prebuilt image from here:
    # https://hub.docker.com/_/redis/
    image: "redis:alpine"

docker-compose command line usage example:

# The following command will create and start all containers in the background
# using docker-compose.yml from current directory
docker-compose up -d

# get help
docker-compose --help

In case you need files from previous folders when building your Dockerfile

You can still use the above solution and place your Dockerfile in a directory such as docker/web/Dockerfile, all you need is to set the build context in your docker-compose.yml like this:

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    ports:
     - "5000:5000"
    volumes:
     - .:/code

This way, you'll be able to have things like this:

config-on-root.ini
docker-compose.yml
docker
+-- web
    +-- Dockerfile
    +-- some-other-config.ini

and a ./docker/web/Dockerfile like this:

FROM alpine:latest

COPY config-on-root.ini /
COPY docker/web/some-other-config.ini /

Here are some quick commands from tldr docker-compose. Make sure you refer to official documentation for more details.

Renaming column names of a DataFrame in Spark Scala

def aliasAllColumns(t: DataFrame, p: String = "", s: String = ""): DataFrame =
{
  t.select( t.columns.map { c => t.col(c).as( p + c + s) } : _* )
}

In case is isn't obvious, this adds a prefix and a suffix to each of the current column names. This can be useful when you have two tables with one or more columns having the same name, and you wish to join them but still be able to disambiguate the columns in the resultant table. It sure would be nice if there were a similar way to do this in "normal" SQL.

flutter corner radius with transparent background

As of May 1st 2019, use BottomSheetTheme.

MaterialApp(
    theme: ThemeData(
      // Draw all modals with a white background and top rounded corners
      bottomSheetTheme: BottomSheetThemeData(
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(10))
        )
      )
    ),

Introduced recently, using a theme to control the sheets style should be the most best to this problem.

If you want to theme different bottom sheets differently, include a new Theme object in the appropriate subtree to override the bottom sheet theme just for that area.

If for some reason you'd still like to override the theme manually when launching a bottom sheet, showBottomSheet and showModalBottomSheet now have a backgroundColor parameter. Use it like this:

 showModalBottomSheet(
    backgroundColor: Colors.transparent,
    context: context,
    builder: (c) {return NavSheet();},
  );

Using the theme allows bottom sheets to be re-used regardless of the app / app's current theme, and has none of the negative side effects of setting canvas color as mentioned.

Difference between Statement and PreparedStatement

PreparedStatement is a very good defense (but not foolproof) in preventing SQL injection attacks. Binding parameter values is a good way to guarding against "little Bobby Tables" making an unwanted visit.

Label axes on Seaborn Barplot

You can also set the title of your chart by adding the title parameter as follows

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

PHP - Indirect modification of overloaded property

Nice you gave me something to play around with

Run

class Sample extends Creator {

}

$a = new Sample ();
$a->role->rolename = 'test';
echo  $a->role->rolename , PHP_EOL;
$a->role->rolename->am->love->php = 'w00';
echo  $a->role->rolename  , PHP_EOL;
echo  $a->role->rolename->am->love->php   , PHP_EOL;

Output

test
test
w00

Class Used

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        $this->{$name} = new Value ( $name, $value );
    }



}

class Value extends Creator {
    private $name;
    private $value;
    function __construct($name, $value) {
        $this->name = $name;
        $this->value = $value;
    }

    function __toString()
    {
        return (string) $this->value ;
    }
}      

Edit : New Array Support as requested

class Sample extends Creator {

}

$a = new Sample ();
$a->role = array (
        "A",
        "B",
        "C" 
);


$a->role[0]->nice = "OK" ;

print ($a->role[0]->nice  . PHP_EOL);

$a->role[1]->nice->ok = array("foo","bar","die");

print ($a->role[1]->nice->ok[2]  . PHP_EOL);


$a->role[2]->nice->raw = new stdClass();
$a->role[2]->nice->raw->name = "baba" ;

print ($a->role[2]->nice->raw->name. PHP_EOL);

Output

 Ok die baba

Modified Class

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;

    }

}

class Value {
    private $name ;
    function __construct($name, $value) {
        $this->{$name} = $value;
        $this->name = $value ;
    }

    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }

        if ($name == $this->name) {
            return $this->value;
        }

        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;
    }

    public function __toString() {
        return (string) $this->name ;
    }   
}

How to set opacity in parent div and not affect in child div?

You can't. Css today simply doesn't allow that.

The logical rendering model is this one :

If the object is a container element, then the effect is as if the contents of the container element were blended against the current background using a mask where the value of each pixel of the mask is .

Reference : css transparency

The solution is to use a different element composition, usually using fixed or computed positions for what is today defined as a child : it may appear logically and visualy for the user as a child but the element doesn't need to be really a child in your code.

A solution using css : fiddle

.parent {
    width:500px;
    height:200px;    
    background-image:url('http://canop.org/blog/wp-content/uploads/2011/11/cropped-bandeau-cr%C3%AAte-011.jpg');
    opacity: 0.2;
}
.child {
    position: fixed;
    top:0;
}

Another solution with javascript : fiddle

Command-line Git on Windows

In windows 8.1, setting the PATH Environment Variable to Git's bin directory didn't work for me. Instead, I had to use the cmd directory C:\Program Files (x86)\Git\cmd.

Credit to @VonC in this question

How to generate a HTML page dynamically using PHP?

I'll just update the code to contain the changes, and comment it to so that you can see what's going on clearly...

<?php   
include("templates/header.htm");   

// Set the default name 
$action = 'index'; 
// Specify some disallowed paths 
$disallowed_paths = array('header', 'footer'); 
if (!empty($_GET['action'])) { 
    $tmp_action = basename($_GET['action']); 
    // If it's not a disallowed path, and if the file exists, update $action 
    if (!in_array($tmp_action, $disallowed_paths) && file_exists("templates/{$tmp_action}.htm")) 
        $action = $tmp_action; 
} 
// Include $action 
include("templates/$action.htm"); 

include("templates/footer.htm");

Get paragraph text inside an element

HTML:

<ul>
  <li onclick="myfunction(this)">
    <span></span>
    <p>This Text</p>
  </li>
</ul>?

JavaScript:

function myfunction(foo) {
    var elem = foo.getElementsByTagName('p');
    var TextInsideLi = elem[0].innerHTML;
}?

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

Simplest way to do a recursive self-join?

Using CTEs you can do it this way

DECLARE @Table TABLE(
        PersonID INT,
        Initials VARCHAR(20),
        ParentID INT
)

INSERT INTO @Table SELECT     1,'CJ',NULL
INSERT INTO @Table SELECT     2,'EB',1
INSERT INTO @Table SELECT     3,'MB',1
INSERT INTO @Table SELECT     4,'SW',2
INSERT INTO @Table SELECT     5,'YT',NULL
INSERT INTO @Table SELECT     6,'IS',5

DECLARE @PersonID INT

SELECT @PersonID = 1

;WITH Selects AS (
        SELECT *
        FROM    @Table
        WHERE   PersonID = @PersonID
        UNION ALL
        SELECT  t.*
        FROM    @Table t INNER JOIN
                Selects s ON t.ParentID = s.PersonID
)
SELECT  *
FROm    Selects

How do I analyze a .hprof file?

If you want a fairly advanced tool to do some serious poking around, look at the Memory Analyzer project at Eclipse, contributed to them by SAP.

Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-memory objects, i.e.

SELECT toString(firstName) FROM com.yourcompany.somepackage.User

Totally brilliant.

Convert an ArrayList to an object array

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

$http.get(...).success is not a function

This might be redundant but the above most voted answer says .then(function (success) and that didn't work for me as of Angular version 1.5.8. Instead use response then inside the block response.data got me my json data I was looking for.

$http({
    method: 'get', 
    url: 'data/data.json'
}).then(function (response) {
    console.log(response, 'res');
    data = response.data;
},function (error){
    console.log(error, 'can not get data.');
});

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

I would suggest Travis for Open source project. It's just simple to configure and use.

Simple steps to setup:

  1. Should have GITHUB account and register in Travis CI website using your GITHUB account.
  2. Add .travis.yml file in root of your project. Add Travis as service in your repository settings page.

Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.

How can I force a hard reload in Chrome for Android

Adding a parameter to url fool browser to load a new page. I wrote a fuction for that purpose:

function forceReload(){
    
    function setUrlParams(url, key, value) {
        url = url.split('?');
        usp = new URLSearchParams(url[1]);
        usp.set(key, value);
        url[1] = usp.toString();
        return url.join('?');
    }
    
    window.location.href =setUrlParams(window.location.href,'_t',Date.now());
}

And you just need to call it:

forceReload();

how do you pass images (bitmaps) between android activities using bundles?

I had to rescale the bitmap a bit to not exceed the 1mb limit of the transaction binder. You can adapt the 400 the your screen or make it dinamic it's just meant to be an example. It works fine and the quality is nice. Its also a lot faster then saving the image and loading it after but you have the size limitation.

public void loadNextActivity(){
    Intent confirmBMP = new Intent(this,ConfirmBMPActivity.class);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Bitmap bmp = returnScaledBMP();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);

    confirmBMP.putExtra("Bitmap",bmp);
    startActivity(confirmBMP);
    finish();

}
public Bitmap returnScaledBMP(){
    Bitmap bmp=null;
    bmp = tempBitmap;
    bmp = createScaledBitmapKeepingAspectRatio(bmp,400);
    return bmp;

}

After you recover the bmp in your nextActivity with the following code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_confirmBMP);
    Intent intent = getIntent();
    Bitmap bitmap = (Bitmap) intent.getParcelableExtra("Bitmap");

}

I hope my answer was somehow helpfull. Greetings

Why is setTimeout(fn, 0) sometimes useful?

Take a look at John Resig's article about How JavaScript Timers Work. When you set a timeout, it actually queues the asynchronous code until the engine executes the current call stack.

How to prevent http file caching in Apache httpd (MAMP)

Based on the example here: http://drupal.org/node/550488

The following will probably work in .htaccess

 <IfModule mod_expires.c>
   # Enable expirations.
   ExpiresActive On

   # Cache all files for 2 weeks after access (A).
   ExpiresDefault A1209600

  <FilesMatch (\.js|\.html)$>
     ExpiresActive Off
  </FilesMatch>
 </IfModule>

jQuery Determine if a matched class has a given id

Let's say that you're iterating through some DOM objects and you wanna find and catch an element with a certain ID

<div id="myDiv">
    <div id="fo"><div>
    <div id="bar"><div>
</div>

You can either write something like to find

$('#myDiv').find('#bar')

Note that if you were to use a class selector, the find method will return all the matching elements.

or you could write an iterating function that will do more advanced work

<div id="myDiv">
    <div id="fo"><div>
    <div id="bar"><div>
    <div id="fo1"><div>
    <div id="bar1"><div>
    <div id="fo2"><div>
    <div id="bar2"><div>
</div>

$('#myDiv div').each(function() {
   if($(this).attr('id') == 'bar1')
       //do something with bar1
});

Same code could be easily modified for class selector.

<div id="myDiv">
    <div class="fo"><div>
    <div class="bar"><div>
    <div class="fo"><div>
    <div class="bar"><div>
    <div class="fo"><div>
    <div class="bar"><div>
</div>

$('#myDiv div').each(function() {
   if($(this).hasClass('bar'))
       //do something with bar
});

I'm glad you solved your problem with index(), what ever works for you.I hope this will help others with the same problem. Cheers :)

Simple PHP form: Attachment to email (code golf)

PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.

You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.

Is it possible to change the package name of an Android app on Google Play?

From Dianne Hackborn:

Things That Cannot Change:

The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.

More on things you cannot change here

Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.

How to take screenshot of a div with JavaScript?

If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers

Example "all-in-one" script script.php

<?php if(isset($_GET['image'])):
    $image = $_GET['image'];

    if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
        $base64 = $match[2];
        $imageBody = base64_decode($base64);
        $imageFormat = $match[1];

        header('Content-type: application/octet-stream');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false); // required for certain browsers
        header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".strlen($imageBody));
        echo $imageBody;
    }
    exit();
endif;?>

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
    $(document).ready(function(){
        var canvas = document.getElementById('canvas');
        var oCtx = canvas.getContext("2d");
        oCtx.beginPath();
        oCtx.moveTo(0,0);
        oCtx.lineTo(300,150);
        oCtx.stroke();

        $('#btn').on('click', function(){
            // opens dialog but location doesnt change due to SaveAs Dialog
            document.location.href = '/script.php?image=' + canvas.toDataURL();
        });
    });
</script>

Where does MAMP keep its php.ini?

I have checked all answers and of course I have used phpinfo() to check the exact location of php.ini. I don't see a File option in the menu bar on my mac. I changed both php.ini and php.ini.temp files in that folder. No vail.

Until I realized that I forgot to uncomment the modified always_populate_raw_post_data line.

Format the date using Ruby on Rails

First you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

Then to format it nicely in the view, you can just use to_s (for the default formatting):

<%= my_date.to_s %>

Note that if you don't put to_s, it will still be called by default if you use it in a view or in a string e.g. the following will also call to_s on the date:

<%= "Here is a date: #{my_date}" %>

or if you want the date formatted in a specific way (eg using "d/m/Y") - you can use strftime as outlined in the other answer.

Understanding repr( ) function in Python

str() is used for creating output for end user while repr() is used for debuggin development.And it's represent the official of object.

Example:

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2018-04-08 18:00:15.178404'
>>> repr(today)
'datetime.datetime(2018, 4, 8, 18, 3, 21, 167886)'

From output we see that repr() shows the official representation of date object.

Difference between h:button and h:commandButton

h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:

<h:form>
    <h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>

this code generates the follwing html:

<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">

whereas the h:button is simpler and just used for static or rule based navigation as follows

<h:button outcome="page.xhtml" value="button"/>

the generated html is

 <title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />

Android - Package Name convention

http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

If you have a company domain www.example.com

Then you should use:

com.example.region.projectname

If you own a domain name like example.co.uk than it should be:

uk.co.example.region.projectname

If you do not own a domain, you should then use your email address:

for [email protected] it should be:

com.example.name.region.projectname

How do you generate a random double uniformly distributed between 0 and 1 from C++?

//Returns a random number in the range (0.0f, 1.0f).
// 0111 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
// seee eeee eeee vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv vvvv
// sign     = 's'
// exponent = 'e'
// value    = 'v'
double DoubleRand() {
  typedef unsigned long long uint64;
  uint64 ret = 0;
  for (int i = 0; i < 13; i++) {
     ret |= ((uint64) (rand() % 16) << i * 4);
  }
  if (ret == 0) {
    return rand() % 2 ? 1.0f : 0.0f;
  }
  uint64 retb = ret;
  unsigned int exp = 0x3ff;
  retb = ret | ((uint64) exp << 52);
  double *tmp = (double*) &retb;
  double retval = *tmp;
  while (retval > 1.0f || retval < 0.0f) {
    retval = *(tmp = (double*) &(retb = ret | ((uint64) (exp--) << 52)));
  }
  if (rand() % 2) {
    retval -= 0.5f;
  }
  return retval;
}

This should do the trick, I used this Wikipedia article to help create this. I believe it to be as good as drand48();

Force browser to refresh css, javascript, etc

If you want to avoid that on client side you can add something like ?v=1.x to css file link, when the file content is changed. for example if there was <link rel="stylesheet" type="text/css" href="css-file-name.css"> you can change it to <link rel="stylesheet" type="text/css" href="css-file-name.css?v=1.1"> this will bypass caching.

Reset par to the default values at startup

dev.off() is the best function, but it clears also all plots. If you want to keep plots in your window, at the beginning save default par settings:

def.par = par()

Then when you use your par functions you still have a backup of default par settings. Later on, after generating plots, finish with:

par(def.par) #go back to default par settings

With this, you keep generated plots and reset par settings.

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

Chart.js canvas resize

This works for me:

<body>
    <form>
        [...]
        <div style="position:absolute; top:60px; left:10px; width:500px; height:500px;">
            <canvas id="cv_values"></canvas>

            <script type="text/javascript">
                var indicatedValueData = {
                    labels: ["1", "2", "3"],
                    datasets: [
                        {
                            [...]
                        };

                var cv_values = document.getElementById("cv_values").getContext("2d");
                var myChart = new Chart(cv_values, { type: "line", data: indicatedValueData });
            </script>
        </div>
    </form>
</body>

The essential fact is that we have to set the size of the canvas in the div-tag.

IE11 prevents ActiveX from running

Here's how I got it working:

  1. Include your URL in IE Trusted Sites

  2. run gpedit.msc (as Admin) and enable the following setting:

gpedit->Local->Computer->Windows Comp->ActiveX Installer->ActiveX installation policy for sites in Trusted Zones

Enabled + Silently,Silently,Prompt

  1. Run gpupdate

  2. Relaunch your Browser

NOTES: Windows 10 EDGE don't have trusted sites, so you have to use IE 11. Lots of folk moaning about that!

Incrementing a date in JavaScript

Incrementing date's year with vanilla js:

start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020

Just in case someone wants to increment other value than the date (day)

Execute a large SQL script (with GO commands)

I accomplished this today by loading my SQL from a text file into one string. I then used the string Split function to separate the string into individual commands which were then sent to the server individually. Simples :)

Just realised that you need to split on \nGO just in case the letters GO appear in any of your table names etc. Guess I was lucky there!

Environment variable substitution in sed

VAR=8675309
echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1' 

where VAR contains what you want to replace the field with

Convert char to int in C and C++

For char or short to int, you just need to assign the value.

char ch = 16;
int in = ch;

Same to int64.

long long lo = ch;

All values will be 16.

Passing a method parameter using Task.Factory.StartNew

The best option is probably to use a lambda expression that closes over the variables you want to display.

However, be careful in this case, especially if you're calling this in a loop. (I mention this since your variable is an "ID", and this is common in this situation.) If you close over the variable in the wrong scope, you can get a bug. For details, see Eric Lippert's post on the subject. This typically requires making a temporary:

foreach(int id in myIdsToCheck)
{
    int tempId = id; // Make a temporary here!
    Task.Factory.StartNew( () => CheckFiles(tempId, theBlockingCollection),
         cancelCheckFile.Token, 
         TaskCreationOptions.LongRunning, 
         TaskScheduler.Default);
}

Also, if your code is like the above, you should be careful with using the LongRunning hint - with the default scheduler, this causes each task to get its own dedicated thread instead of using the ThreadPool. If you're creating many tasks, this is likely to have a negative impact as you won't get the advantages of the ThreadPool. It's typically geared for a single, long running task (hence its name), not something that would be implemented to work on an item of a collection, etc.

ASP.NET MVC DropDownListFor with model of type List<string>

If you have a List of type string that you want in a drop down list I do the following:

EDIT: Clarified, making it a fuller example.

public class ShipDirectory
{
    public string ShipDirectoryName { get; set; }
    public List<string> ShipNames { get; set; }
}

ShipDirectory myShipDirectory = new ShipDirectory()
{
    ShipDirectoryName = "Incomming Vessels",
    ShipNames = new List<string>(){"A", "A B"},
}

myShipDirectory.ShipNames.Add("Aunt Bessy");

@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })

Which gives a drop down list like so:

<select id="ShipNames" name="ShipNames" style="width:500px">
    <option value="">Select a Ship...</option>
    <option>A</option>
    <option>A B</option>
    <option>Aunt Bessy</option>
</select>

To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):

public ActionResult MyActionName(MyViewModel model)

Access the ShipNames value like so: model.ShipNames

If you just want to access the drop down list on post then the signature becomes:

public ActionResult MyActionName(string ShipNames)

EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.

How to compare strings in C conditional preprocessor-directives

I don't think there is a way to do variable length string comparisons completely in preprocessor directives. You could perhaps do the following though:

#define USER_JACK 1
#define USER_QUEEN 2

#define USER USER_JACK 

#if USER == USER_JACK
#define USER_VS USER_QUEEN
#elif USER == USER_QUEEN
#define USER_VS USER_JACK
#endif

Or you could refactor the code a little and use C code instead.

bootstrap responsive table content wrapping

Fine then. You can use CSS word wrap property. Something like this :

td.test /* Give whatever class name you want */
{
width:11em; /* Give whatever width you want */
word-wrap:break-word;
}

Setting Authorization Header of HttpClient

UTF8 Option

request.DefaultRequestHeaders.Authorization = 
new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(
        System.Text.Encoding.UTF8.GetBytes(
           $"{yourusername}:{yourpwd}")));

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

how can I enable PHP Extension intl?

Download the files and try to install them. One or two files may fail to install.

http://www.microsoft.com/en-sg/download/details.aspx?id=30679

Android Studio: Unable to start the daemon process

Not sure this will fix the problem for everyone , But uninstalling java, java SDK and installing the latest version (Version 8) fixed the issue for me ..

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

Java integer to byte array

integer & 0xFF

for the first byte

(integer >> 8) & 0xFF

for the second and loop etc., writing into a preallocated byte array. A bit messy, unfortunately.

Using Exit button to close a winform program

Used Following Code

System.Windows.Forms.Application.Exit( ) 

How to remove foreign key constraint in sql server?

Drop all the foreign keys of a table:

USE [Database_Name]
DECLARE @FOREIGN_KEY_NAME VARCHAR(100)

DECLARE FOREIGN_KEY_CURSOR CURSOR FOR
SELECT name FOREIGN_KEY_NAME FROM sys.foreign_keys WHERE parent_object_id = (SELECT object_id FROM sys.objects WHERE name = 'Table_Name' AND TYPE = 'U')

OPEN FOREIGN_KEY_CURSOR
----------------------------------------------------------
FETCH NEXT FROM FOREIGN_KEY_CURSOR INTO @FOREIGN_KEY_NAME
WHILE @@FETCH_STATUS = 0
    BEGIN
       DECLARE @DROP_COMMAND NVARCHAR(150) = 'ALTER TABLE Table_Name DROP CONSTRAINT' + ' ' + @FOREIGN_KEY_NAME

       EXECUTE Sp_executesql @DROP_COMMAND

       FETCH NEXT FROM FOREIGN_KEY_CURSOR INTO @FOREIGN_KEY_NAME

    END
-----------------------------------------------------------------------------------------------------------------
CLOSE FOREIGN_KEY_CURSOR
DEALLOCATE FOREIGN_KEY_CURSOR

Create stacked barplot where each stack is scaled to sum to 100%

prop.table is a nice friendly way of obtaining proportions of tables.

m <- matrix(1:4,2)

 m
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Leaving margin blank gives you proportions of the whole table

 prop.table(m, margin=NULL)
     [,1] [,2]
[1,]  0.1  0.3
[2,]  0.2  0.4

Giving it 1 gives you row proportions

 prop.table(m, 1)
      [,1]      [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667

And 2 is column proportions

 prop.table(m, 2)
          [,1]      [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286

Space between two rows in a table?

Here's a simple and elegant solution, with a few caveats:

  • You can't actually make the gaps transparent, you need to give them a specific color.
  • You can't round the corners of the borders above & below the gaps
  • You need to know the padding and borders of your table cells

With that in mind, try this:

td {padding:5px 8px;border:2px solid blue;background:#E0E0E0}  /* lets say the cells all have this padding and border, and the gaps should be white */

tr.gapbefore td {overflow:visible}
tr.gapbefore td::before,
tr.gapbefore th::before
{
  content:"";
  display:block;
  position:relative;
  z-index:1;
  width:auto;
  height:0;
  padding:0;
  margin:-5px -10px 5px;  /* 5px = cell top padding, 10px = (cell side padding)+(cell side border width)+(table side border width) */
  border-top:16px solid white;  /* the size & color of the gap you want */
  border-bottom:2px solid blue; /* this replaces the cell's top border, so should be the same as that. DOUBLE IT if using border-collapse:separate */
}

What you're actually doing is sticking a rectangular ::before block into the top of all the cells in the row you want preceded by a gap. These blocks stick out of the cells a bit to overlap the existing borders, hiding them. These blocks are just a top and bottom border sandwiched together: The top border forms the gap, and the bottom border re-creates the appearance of the cells' original top border.

Note that if you have a border around the table itself as well as the cells, you'll need to further increase the horizontal -ve margin of of your 'blocks'. So for a 4px table border, you'd instead use:

margin:-5px -12px 5px;     /* 14px = original 10px + 2px for 'uncollapsed' part of table border */

And if your table uses border-collapse:separate instead of border-collapse:collapse, then you'll need to (a) use the full table border width:

margin:-5px -14px 5px;     /* 14px = original 10px + 4px full width of table border */

... and also (b) replace the double-width of border that now needs to appear below the gap:

border-bottom:4px solid blue;     /* i.e. 4px = cell top border + previous row's bottom border */

The technique is easily adapted to a .gapafter version, if you prefer, or to creating vertical (column) gaps instead of row gaps.

Here's a codepen where you can see it in action: https://codepen.io/anon/pen/agqPpW

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Kafka consumer list

All the consumers per topic

(Replace --zookeeper with --bootstrap-server to get groups stored by newer Kafka clients)

Get all consumers-per-topic as a table of topictabconsumer:

for t in `kafka-consumer-groups.sh --zookeeper <HOST>:2181 --list 2>/dev/null`; do
    echo $t | xargs -I {} sh -c "kafka-consumer-groups.sh --zookeeper <HOST>:2181 --describe --group {} 2>/dev/null | grep ^{} | awk '{print \$2\"\t\"\$1}' "
done > topic-consumer.txt

Make this pairs unique:

cat topic-consumer.txt | sort -u > topic-consumer-u.txt

Get the desired one:

less topic-consumer-u.txt | grep -i <TOPIC>

javascript code to check special characters

You could also do it this way.

specialRegex = /[^A-Z a-z0-9]/ specialRegex.test('test!') // evaluates to true Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character

MVVM Passing EventArgs As Command Parameter

To add to what joshb has stated already - this works just fine for me. Make sure to add references to Microsoft.Expression.Interactions.dll and System.Windows.Interactivity.dll and in your xaml do:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

I ended up using something like this for my needs. This shows that you can also pass a custom parameter:

<i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">

                <i:InvokeCommandAction Command="{Binding Path=DataContext.RowSelectedItem, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
                                       CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
            </i:EventTrigger>
</i:Interaction.Triggers>

How to change the font color of a disabled TextBox?

I've just found a great way of doing that. In my example I'm using a RichTextBox but it should work with any Control:

public class DisabledRichTextBox : System.Windows.Forms.RichTextBox
{
    // See: http://wiki.winehq.org/List_Of_Windows_Messages

    private const int WM_SETFOCUS   = 0x07;
    private const int WM_ENABLE     = 0x0A;
    private const int WM_SETCURSOR  = 0x20;

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (!(m.Msg == WM_SETFOCUS || m.Msg == WM_ENABLE || m.Msg == WM_SETCURSOR))
            base.WndProc(ref m);
    }
}

You can safely set Enabled = true and ReadOnly = false, and it will act like a label, preventing focus, user input, cursor change, without being actually disabled.

See if it works for you. Greetings

Woocommerce, get current product id

Retrieve the ID of the current item in the WordPress Loop.

echo get_the_ID(); 

hence works for the product id too. #tested #woo-commerce

How to understand nil vs. empty vs. blank in Ruby

Everybody else has explained well what is the difference.

I would like to add in Ruby On Rails, it is better to use obj.blank? or obj.present? instead of obj.nil? or obj.empty?.

obj.blank? handles all types nil, '', [], {}, and returns true if values are not available and returns false if values are available on any type of object.

Looking for a short & simple example of getters/setters in C#

This is a basic example of an object "Article" with getters and setters:

  public class Article
    {

        public String title;
        public String link;
        public String description;

        public string getTitle()
        {
            return title;
        }

        public void setTitle(string value)
        {
            title = value;
        }

        public string getLink()
        {
            return link;
        }

        public void setLink(string value)
        {
            link = value;
        }
        public string getDescription()
        {
            return description;
        }

        public void setDescription(string value)
        {
            description = value;
        }
    }

View not attached to window manager crash

See how the Code is working here:

After calling the Async task, the async task runs in the background. that is desirable. Now, this Async task has a progress dialog which is attached to the Activity, if you ask how to see the code:

pDialog = new ProgressDialog(CLASS.this);

You are passing the Class.this as context to the argument. So the Progress dialog is still attached to the activity.

Now consider the scenario: If we try to finish the activity using the finish() method, while the async task is in progress, is the point where you are trying to access the Resource attached to the activity ie the progress bar when the activity is no more there.

Hence you get:

java.lang.IllegalArgumentException: View not attached to the window manager

Solution to this:

1) Make sure that the Dialog box is dismissed or canceled before the activity finishes.

2) Finish the activity, only after the dialog box is dismissed, that is the async task is over.

Table column sizing

Disclaimer: This answer may be a bit old. Since the bootstrap 4 beta. Bootstrap has changed since then.

The table column size class has been changed from this

<th class="col-sm-3">3 columns wide</th>

to

<th class="col-3">3 columns wide</th>

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

Minimal solution that worked for me for current project

  • A create-react-app project
  • Ubuntu / *nix
  • 2020
  • Node 14.7

delete node_modules/browserslist directory in the project

now

npm run build

no longer generates that message

Search File And Find Exact Match And Print Line?

The check has to be like this:

if num == line.split()[0]:

If file.txt has a layout like this:

1 foo
20 bar
30 20

We split up "1 foo" into ['1', 'foo'] and just use the first item, which is the number.

How to save public key from a certificate in .pem format

There are a couple ways to do this.

First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem

If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

openssl> x509 -pubkey -noout -in cert.pem

Output will look something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----

Byte array to image conversion

First Install This Package:

Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007

[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp

Then use Below Code For Cast Byte Array To Image :

Image<Rgba32> image = Image.Load(byteArray); 

For Get ImageFormat Use Below Code:

IImageFormat format = Image.DetectFormat(byteArray);

For Mutate Image Use Below Code:

image.Mutate(x => x.Resize(new Size(1280, 960)));

Text Progress Bar in the Console

It is less than 10 lines of code.

The gist here: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3

import sys


def progress(count, total, suffix=''):
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)

    sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
    sys.stdout.flush()  # As suggested by Rom Ruben

enter image description here

Is std::vector copying the objects with a push_back?

if you want not the copies; then the best way is to use a pointer vector(or another structure that serves for the same goal). if you want the copies; use directly push_back(). you dont have any other choice.

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

How can I set the font-family & font-size inside of a div?

You need a semicolon after font-family: Arial, Helvetica, sans-serif. This will make your updated code the following:

<!DOCTYPE>
<html>
    <head>
        <title>DIV Font</title>

        <style>
            .my_text
            {
                font-family:    Arial, Helvetica, sans-serif;
                font-size:      40px;
                font-weight:    bold;
            }
        </style>
    </head>

    <body>
        <div class="my_text">some text</div>
    </body>
</html>

Read from file or stdin

You may want to look at how this is done in the cat utility, for example.

See code here. If there is no filename as argument, or it is "-", then stdin is used for input. stdin will be there, even if no data is pushed to it (but then, your read call may wait forever).

HTML select dropdown list

If you want to achieve the same for the jquery-ui selectmenu control then you have to set 'display: none' in the open event handler and add '-menu' to the id string.

<select id="myid">
<option value="" disabled="disabled" selected="selected">Please select     name</option>
 <option value="Tom">Tom</option>
 <option value="Marry">Mary</option>
 <option value="Jane">Jane</option>
 <option value="Harry">Harry</option>
 </select>

$('select#listsTypeSelect').selectmenu({
  change: function( event, data ) {
    alert($(this).val());
},
open: function( event, ui ) {
    $('ul#myid-menu li:first-child').css('display', 'none');
}
});

Java - Best way to print 2D array?

Simple and clean way to print a 2D array.

System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

How to set the action for a UIBarButtonItem in Swift

Swift 5

if you have created UIBarButtonItem in Interface Builder and you connected outlet to item and want to bind selector programmatically.

Don't forget to set target and selector.

addAppointmentButton.action = #selector(moveToAddAppointment)
addAppointmentButton.target = self

@objc private func moveToAddAppointment() {
     self.presenter.goToCreateNewAppointment()
}

The 'packages' element is not declared

Oh ok - now I get it. You can ignore this one - the XML for this is just not correct - the packages-element is indeed not declared (there is no reference to a schema or whatever). I think this is a known minor bug that won't do a thing because only NuGet will use this.

See this similar question also.

Difference between SelectedItem, SelectedValue and SelectedValuePath

Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.

To be more specific if you literally want to retrieve Text of Selected Item then you can write:

ListBox1.SelectedItem.Text;

Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.

Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use

ListBox1.SelectedValue

Source

Angular 4 - get input value

If you want to read only one field value, I think, using the template reference variables is the easiest way

Template

<input #phone placeholder="phone number" />

<input type="button" value="Call" (click)="callPhone(phone.value)" />

**Component** 
 
callPhone(phone): void 
{
  
console.log(phone);

}

If you have a number of fields, using the reactive form one of the best ways.

HTTP redirect: 301 (permanent) vs. 302 (temporary)

The main issue with 301 is browser will cache the redirection even if you disabled the redirection from the server level.

Its always better to use 302 if you are enabling the redirection for a short maintenance window.

php: how to get associative array key from numeric index?

$array = array( 'one' =>'value', 'two' => 'value2' );

$allKeys = array_keys($array);
echo $allKeys[0];

Which will output:

one

How do you copy the contents of an array to a std::vector in C++ without looping?

If all you are doing is replacing the existing data, then you can do this

std::vector<int> data; // evil global :)

void CopyData(int *newData, size_t count)
{
   data.assign(newData, newData + count);
}

Normal arguments vs. keyword arguments

I'm surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.

>>> def func(a='a', b='b', c='c', **kwargs):
...    print 'a:%s, b:%s, c:%s' % (a, b, c)
... 
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>> 

How to PUT a json object with an array using curl

Try using a single quote instead of double quotes along with -g

Following scenario worked for me

curl -g -d '{"collection":[{"NumberOfParcels":1,"Weight":1,"Length":1,"Width":1,"Height":1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

WITH

curl -g -d "{'collection':[{'NumberOfParcels':1,'Weight':1,'Length':1,'Width':1,'Height':1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

This especially resolved my error curl command error : bad url colon is first character

Understanding the results of Execute Explain Plan in Oracle SQL Developer

In recent Oracle versions the COST represent the amount of time that the optimiser expects the query to take, expressed in units of the amount of time required for a single block read.

So if a single block read takes 2ms and the cost is expressed as "250", the query could be expected to take 500ms to complete.

The optimiser calculates the cost based on the estimated number of single block and multiblock reads, and the CPU consumption of the plan. the latter can be very useful in minimising the cost by performing certain operations before others to try and avoid high CPU cost operations.

This raises the question of how the optimiser knows how long operations take. recent Oracle versions allow the collections of "system statistics", which are definitely not to be confused with statistics on tables or indexes. The system statistics are measurements of the performance of the hardware, mostly importantly:

  1. How long a single block read takes
  2. How long a multiblock read takes
  3. How large a multiblock read is (often different to the maximum possible due to table extents being smaller than the maximum, and other reasons).
  4. CPU performance

These numbers can vary greatly according to the operating environment of the system, and different sets of statistics can be stored for "daytime OLTP" operations and "nighttime batch reporting" operations, and for "end of month reporting" if you wish.

Given these sets of statistics, a given query execution plan can be evaluated for cost in different operating environments, which might promote use of full table scans at some times or index scans at others.

The cost is not perfect, but the optimiser gets better at self-monitoring with every release, and can feedback the actual cost in comparison to the estimated cost in order to make better decisions for the future. this also makes it rather more difficult to predict.

Note that the cost is not necessarily wall clock time, as parallel query operations consume a total amount of time across multiple threads.

In older versions of Oracle the cost of CPU operations was ignored, and the relative costs of single and multiblock reads were effectively fixed according to init parameters.

How to determine if .NET Core is installed

The following commands are available with .NET Core SDK 2.1 (v2.1.300):

To list all installed .NET Core SDKs use: dotnet --list-sdks

To list all installed .NET Core runtimes use dotnet --list-runtimes

(tested on Windows as of writing, 03 Jun 2018, and again on 23 Aug 2018)

Update as of 24 Oct 2018: Better option is probably now dotnet --info in a terminal or PowerShell window as already mentioned in other answers.

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

Difference in make_shared and normal shared_ptr in C++

Shared_ptr: Performs two heap allocation

  1. Control block(reference count)
  2. Object being managed

Make_shared: Performs only one heap allocation

  1. Control block and object data.

How to implement a property in an interface

You mean like this?

class MyResourcePolicy : IResourcePolicy {
    private string version;

    public string Version {
        get {
            return this.version;
        }
        set {
            this.version = value;
        }
    }
}

Return values from the row above to the current row

This formula does not require a column letter reference ("A", "B", etc.). It returns the value of the cell one row above in the same column.

=INDIRECT(ADDRESS(ROW()-1,COLUMN()))

Difference between database and schema

Schema is a way of categorising the objects in a database. It can be useful if you have several applications share a single database and while there is some common set of data that all application accesses.

get string from right hand side

SQL> select substr('123456',-1,6) from dual;

S
-
6

SQL> select substr('123456',-6,6) from dual;

SUBSTR
------
123456

SQL> select substr('123456',-7,6) from dual;

S
-

If you watch above statements, 3 query gives null value as -7 > length('123456').

So check the length of CONT_PHONE_NUMBERS and PHONE_NUMBERS

Hope this helps you

add item in array list of android

item=sp.getItemAtPosition(i).toString();
list.add(item);
adapter.notifyDataSetChanged () ;

look up ArrayAdapter.notifyDataSetChanged()

Converting Select results into Insert script - SQL Server

It's possible to do via Visual Studio SQL Server Object Explorer.

You can click "View Data" from context menu for necessary table, filter results and save result as script.

Creating a file name as a timestamp in a batch job

I know this thread is old but I just want to add this here because it helped me alot trying to figure this all out and its clean. The nice thing about this is you could put it in a loop for a batch file that's always running. Server up-time log or something. That's what I use it for anyways. I hope this helps someone someday.

@setlocal enableextensions enabledelayedexpansion
@echo off

call :timestamp freshtime freshdate
echo %freshdate% - %freshtime% - Some data >> "%freshdate - Somelog.log"

:timestamp
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
set FreshTime=%hour%:%min%:%secs%

set year=%date:~-4%
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
set day=%date:~7,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
set FreshDate=%month%.%day%.%year%

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I got this error when I was trying to access Bundle data from One Intent by using getInt("ID").

I solved it by using getString("ID").

From Activity1 i had

Intent intent=new Intent(this,ActivityB.class);
intent.putExtra("data",data)// 
startActivity(intent);

On Activity B,

Bundle bundle=getIntent().getExtras();
if(extras!=null){
// int x=extras.getInt("Data"); This Line gave me error int 
x=Integer.parseInt(extras.getString("Data")); // This solved the problem.
}

How to use a WSDL

If you want to add wsdl reference in .Net Core project, there is no "Add web reference" option.

To add the wsdl reference go to Solution Explorer, right-click on the References project item and then click on the Add Connected Service option.

enter image description here

Then click 'Microsoft WCF Web Service Reference':

enter image description here

Enter the file path into URI text box and import the WSDL:

enter image description here

It will generate a simple, very basic WCF client and you to use it something like this:

YourServiceClient client = new YourServiceClient();
client.DoSomething();

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I found this library quite simple and functional (http://kirillsprograms.com/top_Vectors.php). These are bare bone vectors implemented via C++ templates. No fancy stuff - just what you need to do with vectors (add, subtract multiply, dot, etc).

C++ - How to append a char to char*?

The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way

bool AppendCharToCharArray( char *array, size_t n, char c )
{
    size_t sz = std::strlen( array );

    if ( sz + 1 < n ) 
    {
        array[sz] = c;
        array[sz + 1] = '\0';
    }       

    return ( sz + 1 < n );
} 

If you need a function that will contain a copy of the original array plus the given character then it could look the following way

char * CharArrayPlusChar( const char *array, char c )
{
    size_t sz = std::strlen( array );
    char *s = new char[sz + 2];

    std::strcpy( s, array );
    s[sz] = c;
    s[sz + 1] = '\0';

    return ( s );
} 

How to add to an NSDictionary

A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.

create and add:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"];

and retrieve:

int myNumber = [[dict objectForKey:@"A cool number"] intValue];

Copy files on Windows Command Line with Progress

Here is the script I use:

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
mode con:cols=210 lines=50
ECHO Starting 1-way backup of MEDIA(M:) to BACKUP(G:)...
robocopy.exe M:\ G:\ *.* /E /PURGE /SEC /NP /NJH /NJS /XD "$RECYCLE.BIN" "System Volume Information" /TEE /R:5 /COPYALL /LOG:from_M_to_G.log
ECHO Finished with backup.
pause

How to update npm

To get the latest stable version just run

npm install npm@latest -g

It worked just fine for me!

Table overflowing outside of div

overflow-x: auto;
overflow-y : hidden;

Apply the styling above to the parent div.

Finding local IP addresses using Python's stdlib

This isn't very Pythonic, but it works reliably on Windows.

def getWinIP(version = 'IPv4'):
    import subprocess
    if version not in ['IPv4', 'IPv6']:
        print 'error - protocol version must be "IPv4" or "IPv6"'
        return None
    ipconfig = subprocess.check_output('ipconfig')
    my_ip = []
    for line in ipconfig.split('\n'):
        if 'Address' in line and version in line:
            my_ip.append(line.split(' : ')[1].strip())
    return my_ip

print getWinIP()

Yeah, it's a hack, but at times I don't feel like second-guessing an operating system, and just go ahead and use what's built-in and works.

newline in <td title="">

The jquery colortip plugin also supports <br> tags in the title attribute, you might want to look into that one.

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

open key.properties and check your path is correct. (replace from \ to /)

example:-

replace from "storeFile=D:\Projects\Flutter\Key\key.jks" to "storeFile=D:/Projects/Flutter/Key/key.jks"

How to send parameters from a notification-click to an activity?

Encounter same issue here. I resolve it by using different request code, use same id as notification, while creating PendingIntent. but still don't know why this should be done.

PendingIntent contentIntent = PendingIntent.getActivity(context, **id**, notificationIntent, 0);
notif.contentIntent = contentIntent;
nm.notify(**id**, notif);

Repository Pattern Step by Step Explanation

This is a nice example: The Repository Pattern Example in C#

Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:

  • for reading, it creates the query satisfying the supplied criteria and returns the result set
  • for writing, it issues the commands necessary to make the underlying persistence engine (e.g. an SQL database) save the data

Raising a number to a power in Java

You should use below method-

Math.pow(double a, double b)

Returns the value of the first argument raised to the power of the second argument.

CodeIgniter 500 Internal Server Error

This probably isn't relevant any more to this thread, but hopefully helpful to somebody. I've had 500 errors for the past hour as I had a controller return an array not supported by the php version ran on my (crappy) server. Seems trivial but had the hallmarks of a codeigniter error.

I had to use:

class emck_model extends CI_Model {

    public function getTiles(){

        return array(...);

    }

} 

Instead of

class emck_model extends CI_Model {

    public function getTiles(){

        return [...];

    }

}

Cheers

How do I import a .dmp file into Oracle?

Presuming you have a .dmp file created by oracle exp then

imp help=y

will be your friend. It will lead you to

imp file=<file>.dmp show=y

to see the contents of the dump and then something like

imp scott/tiger@example file=<file>.dmp fromuser=<source> touser=<dest>

to import from one user to another. Be prepared for a long haul though if it is a complicated schema as you will need to precreate all referenced schema users, and tablespaces to make the imp work correctly

How do I publish a UDP Port on Docker?

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

-p 53160:53160/udp

Full command

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

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

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

EXPOSE 8285/udp

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

" netsh wlan start hostednetwork " command not working no matter what I try

At first simply uninstall wifi drivers and softwares just keep wifi drivers + from device manager....network adapters...remove all virtual connections

then

Press the Windows + R key combination to bring up a run box, type ncpa.cpl and hit enter.

netsh wlan set hostednetwork mode=allow ssid=”How-To Geek” key=”Pa$$w0rd”

netsh wlan start hostednetwork

netsh wlan show hostednetwork

its working for me and on others PC.

SQL Server Operating system error 5: "5(Access is denied.)"

SQL Server database engine service account must have permissions to read/write in the new folder.

Check out this

To fix, I did the following:

Added the Administrators Group to the file security permissions with full control for the Data file (S:) and the Log File (T:).

Attached the database and it works fine.

enter image description here

enter image description here

How to select distinct query using symfony2 doctrine query builder?

Just open your repository file and add this new function, then call it inside your controller:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

Then within your controller:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

Good luck!

How to change default install location for pip

Open Terminal and type:

pip config set global.target /Users/Bob/Library/Python/3.8/lib/python/site-packages

except instead of

/Users/Bob/Library/Python/3.8/lib/python/site-packages

you would use whatever directory you want.

Service will not start: error 1067: the process terminated unexpectedly

This error message appears if the Windows service launcher has quit immediately after being started. This problem usually happens because the license key has not been correctly deployed(license.txt file in the license folder). If service is not strtign with correct key, just put incorrect key and try to start. Once started, place the correct key, it will work.

New lines inside paragraph in README.md

If you want to be a little bit fancier you can also create it as an html list to create something like bullets or numbers using ul or ol.

<ul>
<li>Line 1</li>
<li>Line 2</li>
</ul>

How to sort an array of objects in Java?

import java.util.Collections;

import java.util.List;

import java.util.ArrayList;


public class Test {

public static void main(String[] args) {

   List<Student> str = new ArrayList<Student>();

   str.add(new Student(101, "aaa"));

   str.add(new Student(104, "bbb"));

   str.add(new Student(103, "ccc"));

   str.add(new Student(105, "ddd"));

   str.add(new Student(104, "eee"));

   str.add(new Student(102, "fff"));




   Collections.sort(str);
    for(Student student : str) {

        System.out.println(student);
    }

}
}

How do I call ::CreateProcess in c++ to launch a Windows executable?

Something like this:

STARTUPINFO info={sizeof(info)};
PROCESS_INFORMATION processInfo;
if (CreateProcess(path, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo))
{
    WaitForSingleObject(processInfo.hProcess, INFINITE);
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);
}

Using jQuery how to get click coordinates on the target element

see here enter link description here

html

<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>

css

#myPosition{
  background-color:red;
  height:200px;
  width:200px;
}

jquery

$(document).ready(function(){
    $("#myPosition").click(function(e){
       var elm = $(this);
       var xPos = e.pageX - elm.offset().left;
       var yPos = e.pageY - elm.offset().top;
       alert("X position: " + xPos + ", Y position: " + yPos);
    });
});

How to create a Rectangle object in Java using g.fillRect method

Try this:

public void paint (Graphics g) {    
    Rectangle r = new Rectangle(xPos,yPos,width,height);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());  
}

[edit]

// With explicit casting
public void paint (Graphics g) {    
        Rectangle r = new Rectangle(xPos, yPos, width, height);
        g.fillRect(
           (int)r.getX(),
           (int)r.getY(),
           (int)r.getWidth(),
           (int)r.getHeight()
        );  
    }

How to override !important?

This can help too

td[style] {height: 50px !important;}

This will override any inline style

How do I initialize an empty array in C#?

In .NET 4.6 the preferred way is to use a new method, Array.Empty:

String[] a = Array.Empty<string>();

The implementation is succinct, using how static members in generic classes behave in .Net:

public static T[] Empty<T>()
{
    return EmptyArray<T>.Value;
}

// Useful in number of places that return an empty byte array to avoid
// unnecessary memory allocation.
internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

(code contract related code removed for clarity)

See also:

'python3' is not recognized as an internal or external command, operable program or batch file

In my case I have a git hook on commit, specified by admin. So it was not very convenient for me to change the script (with python3 calls).

And the simplest workaround was just to copy python.exe to python3.exe.

Now I could launch both python and python3.

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

Pass multiple complex objects to a post/put Web API method

Create one complex object to combine Content and Config in it as others mentioned, use dynamic and just do a .ToObject(); as:

[HttpPost]
public void StartProcessiong([FromBody] dynamic obj)
{
   var complexObj= obj.ToObject<ComplexObj>();
   var content = complexObj.Content;
   var config = complexObj.Config;
}

How to style a div to be a responsive square?

HTML

<div class='square-box'>
    <div class='square-content'>
        <h3>test</h3>
    </div>
</div>

CSS

.square-box{
    position: relative;
    width: 50%;
    overflow: hidden;
    background: #4679BD;
}
.square-box:before{
    content: "";
    display: block;
    padding-top: 100%;
}
.square-content{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    color: white;
    text-align: center;
}

http://jsfiddle.net/38Tnx/1425/

Timeout for python requests.get entire response

Set the timeout parameter:

r = requests.get(w, verify=False, timeout=10) # 10 seconds

As long as you don't set stream=True on that request, this will cause the call to requests.get() to timeout if the connection takes more than ten seconds, or if the server doesn't send data for more than ten seconds.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...

Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:

https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new

The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.

For instance, where I had:

$_SERVER['SERVER_NAME']

I've put instead:

filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)

You have the filter_input and filters doc here:

http://www.php.net/manual/en/function.filter-input.php

http://www.php.net/manual/en/filter.filters.php

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

If you wanted just a Date, you can do Date.strptime(invoice.date.to_s, '%s') where invoice.date comes in the form of anFixnum and then converted to a String.

checking for typeof error in JS

Thanks @Trott for your code, I just used the same code and added with a real time working example for the benefit of others.

_x000D_
_x000D_
<html>_x000D_
<body >_x000D_
_x000D_
<p>The **instanceof** operator returns true if the specified object is an instance of the specified object.</p>_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
 var myError = new Error("TypeError: Cannot set property 'innerHTML' of null"); // error type when element is not defined_x000D_
 myError instanceof Error // true_x000D_
 _x000D_
 _x000D_
 _x000D_
 _x000D_
 function test(){_x000D_
 _x000D_
 var v1 = document.getElementById("myid").innerHTML ="zunu"; // to change with this_x000D_
 _x000D_
 try {_x000D_
    var v1 = document.getElementById("myidd").innerHTML ="zunu"; // exception caught_x000D_
    } _x000D_
    _x000D_
 catch (e) {_x000D_
    if (e instanceof Error) {_x000D_
   console.error(e.name + ': ' + e.message) // error will be displayed at browser console_x000D_
    }_x000D_
  }_x000D_
  finally{_x000D_
  var v1 = document.getElementById("myid").innerHTML ="Text Changed to Zunu"; // finally innerHTML changed to this._x000D_
 }_x000D_
 _x000D_
 }_x000D_
 _x000D_
</script>_x000D_
<p id="myid">This text will change</p>_x000D_
<input type="button" onclick="test();">_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

C# refresh DataGridView when updating or inserted on another form

// Form A
public void loaddata()
{
    //do what you do in load data in order to update data in datagrid
}

then on Form B define:

// Form B
FormA obj = (FormA)Application.OpenForms["FormA"];

private void button1_Click(object sender, EventArgs e)
{
    obj.loaddata();
    datagridview1.Update();
    datagridview1.Refresh();
}

Under which circumstances textAlign property works in Flutter?

You can use the container, It will help you to set the alignment.

Widget _buildListWidget({Map reminder}) {
return Container(
  color: Colors.amber,
  alignment: Alignment.centerLeft,
  padding: EdgeInsets.all(20),
  height: 80,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Container(
        alignment: Alignment.centerLeft,
        child: Text(
          reminder['title'],
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            color: Colors.black,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        child: Text(
          reminder['Date'],
          textAlign: TextAlign.right,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
    ],
  ),
);
}

Private vs Protected - Visibility Good-Practice Concern

Well it is all about encapsulation if the paybill classes handles billing of payment then in product class why would it needs the whole process of billing process i.e payment method how to pay where to pay .. so only letting what are used for other classes and objects nothing more than that public for those where other classes would use too, protected for those limit only for extending classes. As you are madara uchiha the private is like "limboo" you can see it (you class only single class).

JQuery confirm dialog

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

Fastest way to flatten / un-flatten nested JSON objects

Here's another approach that runs slower (about 1000ms) than the above answer, but has an interesting idea :-)

Instead of iterating through each property chain, it just picks the last property and uses a look-up-table for the rest to store the intermediate results. This look-up-table will be iterated until there are no property chains left and all values reside on uncocatenated properties.

JSON.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
        props = Object.keys(data),
        result, p;
    while(p = props.shift()) {
        var m = regex.exec(p),
            target;
        if (m.index) {
            var rest = p.slice(0, m.index);
            if (!(rest in data)) {
                data[rest] = m[2] ? [] : {};
                props.push(rest);
            }
            target = data[rest];
        } else {
            target = result || (result = (m[2] ? [] : {}));
        }
        target[m[2] || m[1]] = data[p];
    }
    return result;
};

It currently uses the data input parameter for the table, and puts lots of properties on it - a non-destructive version should be possible as well. Maybe a clever lastIndexOf usage performs better than the regex (depends on the regex engine).

See it in action here.

How to prevent SIGPIPEs (or handle them properly)

Under a modern POSIX system (i.e. Linux), you can use the sigprocmask() function.

#include <signal.h>

void block_signal(int signal_to_block /* i.e. SIGPIPE */ )
{
    sigset_t set;
    sigset_t old_state;

    // get the current state
    //
    sigprocmask(SIG_BLOCK, NULL, &old_state);

    // add signal_to_block to that existing state
    //
    set = old_state;
    sigaddset(&set, signal_to_block);

    // block that signal also
    //
    sigprocmask(SIG_BLOCK, &set, NULL);

    // ... deal with old_state if required ...
}

If you want to restore the previous state later, make sure to save the old_state somewhere safe. If you call that function multiple times, you need to either use a stack or only save the first or last old_state... or maybe have a function which removes a specific blocked signal.

For more info read the man page.

How do I autoindent in Netbeans?

I have netbeans 6.9.1 open right now and ALT+SHIFT+F indents only the lines you have selected.

If no lines are selected then it will indent the whole document you are in.

1 possibly unintended behavior is that if you have selected ONLY 1 line, it must be selected completely, otherwise it does nothing. But you don't have to completely select the last line of a group nor the first.

I expected it to indent only one line by just selecting the first couple of chars but didn't work, yea i know i am lazy as hell...

Changing fonts in ggplot2

Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.

Using FileUtils in eclipse

<!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.io -->
<dependency>
    <groupId>org.apache.directory.studio</groupId>
    <artifactId>org.apache.commons.io</artifactId>
    <version>2.4</version>
</dependency>

Add above dependency in pom.xml file

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

I was facing the Same Error.

Solution: The name of the variable in the View through which we are passing value to Controller should Match the Name of Variable on Controller Side.

.csHtml (View) :

@Html.ActionLink("Edit", "Edit" , new { id=item.EmployeeId })

.cs (Controller Method):

 [HttpGet]
            public ActionResult Edit(int id)
            {
                EmployeeContext employeeContext = new EmployeeContext();
                Employee employee = employeeContext.Employees.Where(emp => emp.EmployeeId == id).First();
                return View(employee);
            }

How to set "value" to input web element using selenium?

As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");