Programs & Examples On #Quotation marks

Java - Including variables within strings?

Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,

String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);

results in string containing the following:

A string of ponies.

More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

How to set MimeBodyPart ContentType to "text/html"?

What about using:

mime_body_part.setHeader("Content-Type", "text/html");

In the documentation of getContentType it says that the value returned is found using getHeader(name). So if you set the header using setHeader I guess everything should be fine.

Binding multiple events to a listener (without JQuery)?

In POJS, you add one listener at a time. It is not common to add the same listener for two different events on the same element. You could write your own small function to do the job, e.g.:

/* Add one or more listeners to an element
** @param {DOMElement} element - DOM element to add listeners to
** @param {string} eventNames - space separated list of event names, e.g. 'click change'
** @param {Function} listener - function to attach for each event as a listener
*/
function addListenerMulti(element, eventNames, listener) {
  var events = eventNames.split(' ');
  for (var i=0, iLen=events.length; i<iLen; i++) {
    element.addEventListener(events[i], listener, false);
  }
}

addListenerMulti(window, 'mousemove touchmove', function(){…});

Hopefully it shows the concept.

Edit 2016-02-25

Dalgard's comment caused me to revisit this. I guess adding the same listener for multiple events on the one element is more common now to cover the various interface types in use, and Isaac's answer offers a good use of built–in methods to reduce the code (though less code is, of itself, not necessarily a bonus). Extended with ECMAScript 2015 arrow functions gives:

function addListenerMulti(el, s, fn) {
  s.split(' ').forEach(e => el.addEventListener(e, fn, false));
}

A similar strategy could add the same listener to multiple elements, but the need to do that might be an indicator for event delegation.

How to add new column to MYSQL table?

ALTER TABLE `stor` ADD `buy_price` INT(20) NOT NULL ;

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

Your indexes probably contains duplicated values.

import pandas as pd

T1_INDEX = [
    0,
    1,  # <= !!! if I write e.g.: "0" here then it fails
    0.2,
]
T1_COLUMNS = [
    'A', 'B', 'C', 'D'
]
T1 = [
    [1.0, 1.1, 1.2, 1.3],
    [2.0, 2.1, 2.2, 2.3],
    [3.0, 3.1, 3.2, 3.3],
]

T2_INDEX = [
    1.2,
    2.11,
]

T2_COLUMNS = [
    'D', 'E', 'F',
]
T2 = [
    [54.0, 5324.1, 3234.2],
    [55.0, 14.5324, 2324.2],
    # [3.0, 3.1, 3.2],
]
df1 = pd.DataFrame(T1, columns=T1_COLUMNS, index=T1_INDEX)
df2 = pd.DataFrame(T2, columns=T2_COLUMNS, index=T2_INDEX)


print(pd.concat([pd.DataFrame({})] + [df2, df1], axis=1))

How to filter array in subdocument with MongoDB

Use $filter aggregation

Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.

db.test.aggregate([
    {$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
    {$project: {
        list: {$filter: {
            input: "$list",
            as: "list",
            cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
        }}
    }}
]);

What is the simplest SQL Query to find the second largest value?

Query to find the 2nd highest number in a row-

select Top 1 (salary) from XYZ
where Salary not in (select distinct TOP 1(salary) from XYZ order by Salary desc)
ORDER BY Salary DESC

By changing the highlighted Top 1 to TOP 2, 3 or 4 u can find the 3rd, 4th and 5th highest respectively.

how to set mongod --dbpath

For me it must have:

mongod --dbpath=/whatever/data/path

Generating a unique machine id

Try this one, it gives a unique hard disk ID: Port of DiskId32 for Delphi 7-2010.

C# listView, how do I add items to columns 2, 3 and 4 etc?

You can add items / sub-items to the ListView like:

ListViewItem item = new ListViewItem(new []{"1","2","3","4"});
listView1.Items.Add(item);

But I suspect your problem is with the View Type. Set it in the designer to Details or do the following in code:

listView1.View = View.Details;

C++ compiling on Windows and Linux: ifdef switch

It depends on the used compiler.

For example, Windows' definition can be WIN32 or _WIN32.

And Linux' definition can be UNIX or __unix__ or LINUX or __linux__.

How Big can a Python List Get?

In casual code I've created lists with millions of elements. I believe that Python's implementation of lists are only bound by the amount of memory on your system.

In addition, the list methods / functions should continue to work despite the size of the list.

If you care about performance, it might be worthwhile to look into a library such as NumPy.

Instantiating a generic class in Java

For Java 8 ....

There is a good solution at https://stackoverflow.com/a/36315051/2648077 post.

This uses Java 8 Supplier functional interface

Expand a div to fill the remaining width

I just discovered the magic of flex boxes (display: flex). Try this:

<style>
  #box {
    display: flex;
  }
  #b {
    flex-grow: 100;
    border: 1px solid green;
  }
</style>
<div id='box'>
 <div id='a'>Tree</div>
 <div id='b'>View</div>
</div>

Flex boxes give me the control I've wished css had for 15 years. Its finally here! More info: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Oracle find a constraint

To get a more detailed description (which table/column references which table/column) you can run the following query:

SELECT   uc.constraint_name||CHR(10)
   ||      '('||ucc1.TABLE_NAME||'.'||ucc1.column_name||')' constraint_source
   ,       'REFERENCES'||CHR(10)
   ||      '('||ucc2.TABLE_NAME||'.'||ucc2.column_name||')' references_column
FROM user_constraints uc ,
  user_cons_columns ucc1 ,
  user_cons_columns ucc2
WHERE uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION        = ucc2.POSITION -- Correction for multiple column primary keys.
AND uc.constraint_type   = 'R'
AND uc.constraint_name   = 'SYS_C00381400'
ORDER BY ucc1.TABLE_NAME ,
  uc.constraint_name;

From here.

Adjusting HttpWebRequest Connection Timeout in C#

From the documentation of the HttpWebRequest.Timeout property:

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

Is it possible that your DNS query is the cause of the timeout?

grep output to show only matching file

grep -l 

(That's a lowercase L)

Difference between getAttribute() and getParameter()

Another case when you should use .getParameter() is when forwarding with parameters in jsp:

<jsp:forward page="destination.jsp">
    <jsp:param name="userName" value="hamid"/>
</jsp:forward>

In destination.jsp, you can access userName like this:

request.getParameter("userName")

How do I get unique elements in this array?

Have you looked at this page?

http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

That might save you some time?

eg db.addresses.distinct("zip-code");

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

Does my application "contain encryption"?

Found some of these answers very useful, but wanted to add this URL for completeness since it walks you through the questions:

https://itunespartner.apple.com/en/apps/faq/Managing%20Your%20Apps_Export%20Compliance#21109148

Cannot open solution file in Visual Studio Code

Use vscode-solution-explorer extension:

This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.

https://github.com/fernandoescolar/vscode-solution-explorer

enter image description here

Thanks @fernandoescolar

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

How does one represent the empty char?

String before = EMPTY_SPACE+TAB+"word"+TAB+EMPTY_SPACE;

Where EMPTY_SPACE = " " (this is String) TAB = '\t' (this is Character)

String after = before.replaceAll(" ", "").replace('\t', '\0');

means after = "word"

How to install Cmake C compiler and CXX compiler

The approach I use is to start the "Visual Studio Command Prompt" which can be found in the Start menu. E.g. my visual studio 2010 Express install has a shortcute Visual Studio Command Prompt (2010) at Start Menu\Programs\Microsoft Visual Studio 2010\Visual Studio Tools.

This shortcut prepares an environment by calling a script vcvarsall.bat where the compiler, linker, etc. are setup from the right Visual Studio installation.

Alternatively, if you already have a prompt open, you can prepare the environment by calling a similar script:

:: For x86 (using the VS100COMNTOOLS env-var)
call "%VS100COMNTOOLS%"\..\..\VC\bin\vcvars32.bat

or

:: For amd64 (using the full path)
call C:\Program Files\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat

However:

Your output (with the '$' prompt) suggests that you are attempting to run CMake from a MSys shell. In that case it might be better to run CMake for MSys or MinGW, by explicitly specifying a makefile generator:

cmake -G"MSYS Makefiles"
cmake -G"MinGW Makefiles"

Run cmake --help to get a list of all possible generators.

How can I see what has changed in a file before committing to git?

Remember, you're committing changes, not files.

For this reason, it's very rare that I don't use git add -p (or the magit equivalent) to add my changes.

ng-repeat finish event

If you simply want to execute some code at the end of the loop, here's a slightly simpler variation that doesn't require extra event handling:

<div ng-controller="Ctrl">
  <div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
    thing {{thing}}
  </div>
</div>
function Ctrl($scope) {
  $scope.things = [
    'A', 'B', 'C'  
  ];
}

angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
      // iteration is complete, do whatever post-processing
      // is necessary
      element.parent().css('border', '1px solid black');
    }
  };
});

See a live demo.

BASH Syntax error near unexpected token 'done'

Had similar problems just now and these are two separate instances and solutions that worked for me:

Case 1. Basically, had a space after the last command within my newline-separated for-loop, eg. (imagining that | here represents the carat in a text editor showing where you are writing), this is what I saw when clicking around the end of the line of the last command in the loop:

for f in $pathToFiles
do
   $stuff |
done

Notice the space before before the carat (so far as I know, this is something cat has no option do display visually (one way you could test is with something like od -bc yourscript.sh)). Changing the code to

for f in $pathToFiles
do
   $stuff| <--- notice the carat shows no ending space before the newline
done

fixed the problem.

Case 2. Was using a pseudo try-catch block for the for-loop (see https://stackoverflow.com/a/22010339/8236733) like

{
for f in $pathToFiles
do
   { $stuff } || { echo "Failed to complete stuff"; exit 255; }
done
} || { echo "Failed to complete loop"; exit 255; }

and apparently bash did not like the nested {}s. Changing to

{
for f in $pathToFiles
do
   $stuff
done
} || { echo "Failed to complete loop"; exit 255; }

fixed the problem in this case. If anyone can further explain either of these cases, please let me know more about them in the comments.

JavaScript by reference vs. by value

My understanding is that this is actually very simple:

  • Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object.
  • Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  • However, changing a property of an object referenced by a variable does change the underlying object.

So, to work through some of your examples:

function f(a,b,c) {
    // Argument a is re-assigned to a new value.
    // The object or primitive referenced by the original a is unchanged.
    a = 3;
    // Calling b.push changes its properties - it adds
    // a new property b[b.length] with the value "foo".
    // So the object referenced by b has been changed.
    b.push("foo");
    // The "first" property of argument c has been changed.
    // So the object referenced by c has been changed (unless c is a primitive)
    c.first = false;
}

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false

Example 2:

var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4";   // a is now ["1", "4", {foo:"bar"}]; b still has the value
              // it had at the time of assignment
a[2] = "5";   // a is now ["1", "4", "5"]; c still has the value
              // it had at the time of assignment, i.e. a reference to
              // the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"

React setState not updating state

I had the same situation with some convoluted code, and nothing from the existing suggestions worked for me.

My problem was that setState was happening from callback func, issued by one of the components. And my suspicious is that the call was occurring synchronously, which prevented setState from setting state at all.

Simply put I have something like this:

render() {
    <Control
        ref={_ => this.control = _}
        onChange={this.handleChange}
        onUpdated={this.handleUpdate} />
}

handleChange() {
    this.control.doUpdate();
}

handleUpdate() {
    this.setState({...});
}

The way I had to "fix" it was to put doUpdate() into setTimeout like this:

handleChange() {
    setTimeout(() => { this.control.doUpdate(); }, 10);
}

Not ideal, but otherwise it would be a significant refactoring.

Lua string to int

You can force an implicit conversion by using a string in an arithmetic operations as in a= "10" + 0, but this is not quite as clear or as clean as using tonumber explicitly.

iOS - Ensure execution on main thread

i think this is cool, even tho in general its good form to leave the caller of a method responsible for ensuring its called on the right thread.

if (![[NSThread currentThread] isMainThread]) {
    [self performSelector:_cmd onThread:[NSThread mainThread] withObject:someObject waitUntilDone:NO];
    return;
}

SSRS the definition of the report is invalid

A very cryptic message for what my issue was.

I had changed the names of the parameters, but did not update these names in the dataset.

How to check if a file exists in a folder?

This helped me:

bool fileExists = (System.IO.File.Exists(filePath) ? true : false);

CSS/HTML: Create a glowing border around an Input Field

_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
    $(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
    $(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
  color:red;   _x000D_
}_x000D_
.form-fild {_x000D_
 position: relative;_x000D_
 margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
 position: absolute;_x000D_
 top: 5px;_x000D_
 left: 10px;_x000D_
 padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
 top: -25px;_x000D_
 left: 10px;_x000D_
 /*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
 padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
 padding: 10px;_x000D_
 width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
 -webkit-transition: all 0.2s ease-in-out;_x000D_
       -moz-transition: all 0.2s ease-in-out;_x000D_
         -o-transition: all 0.2s ease-in-out;_x000D_
            transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
 <div class="row">_x000D_
     <form>_x000D_
        <div class="form-fild">_x000D_
            <label>Name :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Email :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Number :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Message :</label>_x000D_
            <textarea cols="10" rows="5"></textarea>_x000D_
        </div>_x000D_
    </form>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to verify that a specific method was not called using Mockito?

Use the second argument on the Mockito.verify method, as in:

Mockito.verify(dependency, Mockito.times(0)).someMethod()

Most efficient way to get table row count

Next to the information_schema suggestion, this:

SELECT id FROM table ORDER BY id DESC LIMIT 1

should also be very fast, provided there's an index on the id field (which I believe must be the case with auto_increment)

np.mean() vs np.average() in Python NumPy?

In your invocation, the two functions are the same.

average can compute a weighted average though.

Doc links: mean and average

Python loop that also accesses previous and next values

This should do the trick.

foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
    if obj == foo:
        if index > 0:
            previous = objects[index - 1]
        if index < (l - 1):
            next_ = objects[index + 1]

Here's the docs on the enumerate function.

Sublime Text 3, convert spaces to tabs

At the bottom of the Sublime window, you'll see something representing your tab/space setting.

You'll then get a dropdown with a bunch of options. The options you care about are:

  • Convert Indentation to Spaces
  • Convert Indentation to Tabs

Apply your desired setting to the entire document.

Hope this helps.

How to properly seed random number generator

It's nano seconds, what are the chances of getting the same seed twice.
Anyway, thanks for the help, here is my end solution based on all the input.

package main

import (
    "math/rand"
    "time"
)

func init() {
    rand.Seed(time.Now().UTC().UnixNano())
}

// generates a random string
func srand(min, max int, readable bool) string {

    var length int
    var char string

    if min < max {
        length = min + rand.Intn(max-min)
    } else {
        length = min
    }

    if readable == false {
        char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    } else {
        char = "ABCDEFHJLMNQRTUVWXYZabcefghijkmnopqrtuvwxyz23479"
    }

    buf := make([]byte, length)
    for i := 0; i < length; i++ {
        buf[i] = char[rand.Intn(len(char)-1)]
    }
    return string(buf)
}

// For testing only
func main() {
    println(srand(5, 5, true))
    println(srand(5, 5, true))
    println(srand(5, 5, true))
    println(srand(5, 5, false))
    println(srand(5, 7, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 10, false))
    println(srand(5, 50, true))
    println(srand(5, 4, true))
    println(srand(5, 400, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
    println(srand(6, 5, true))
}

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

SaveFileDialog setting default path and file type?

Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

Java ElasticSearch None of the configured nodes are available

NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{UfB9geJCR--spyD7ewmoXQ}{192.168.1.245}{192.168.1.245:9300}]]

In my case it was the difference in versions. If you check the logs in elasticsearch cluster you will see.

Elasticsearch logs

[node1] exception caught on transport layer [NettyTcpChannel{localAddress=/192.168.1.245:9300, remoteAddress=/172.16.1.47:65130}], closing connection
java.lang.IllegalStateException: Received message from unsupported version: [5.0.0] minimal compatible version is: [5.6.0]

I was using elasticsearch client and transport version 5.1.1. And my elasticsearch cluster version was in 6. So I changes my library version to 5.4.3.

How to convert std::string to LPCSTR?

The easiest way to convert a std::string to a LPWSTR is in my opinion:

  1. Convert the std::string to a std::vector<wchar_t>
  2. Take the address of the first wchar_t in the vector.

std::vector<wchar_t> has a templated ctor which will take two iterators, such as the std::string.begin() and .end() iterators. This will convert each char to a wchar_t, though. That's only valid if the std::string contains ASCII or Latin-1, due to the way Unicode values resemble Latin-1 values. If it contains CP1252 or characters from any other encoding, it's more complicated. You'll then need to convert the characters.

CSS - How to Style a Selected Radio Buttons Label?

_x000D_
_x000D_
.radio-toolbar input[type="radio"] {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
.radio-toolbar label {_x000D_
  display: inline-block;_x000D_
  background-color: #ddd;_x000D_
  padding: 4px 11px;_x000D_
  font-family: Arial;_x000D_
  font-size: 16px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.radio-toolbar input[type="radio"]:checked+label {_x000D_
  background-color: #bbb;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
  <input type="radio" id="radio1" name="radios" value="all" checked>_x000D_
  <label for="radio1">All</label>_x000D_
_x000D_
  <input type="radio" id="radio2" name="radios" value="false">_x000D_
  <label for="radio2">Open</label>_x000D_
_x000D_
  <input type="radio" id="radio3" name="radios" value="true">_x000D_
  <label for="radio3">Archived</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

First of all, you probably want to add the name attribute on the radio buttons. Otherwise, they are not part of the same group, and multiple radio buttons can be checked.

Also, since I placed the labels as siblings (of the radio buttons), I had to use the id and for attributes to associate them together.

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

See Heroku “psql: FATAL: remaining connection slots are reserved for non-replication superuser connections”:

Heroku sometimes has a problem with database load balancing.

André Laszlo, markshiz and me all reported dealing with that in comments on the question.

To save you the support call, here's the response I got from Heroku Support for a similar issue:

Hello,

One of the limitations of the hobby tier databases is unannounced maintenance. Many hobby databases run on a single shared server, and we will occasionally need to restart that server for hardware maintenance purposes, or migrate databases to another server for load balancing. When that happens, you'll see an error in your logs or have problems connecting. If the server is restarting, it might take 15 minutes or more for the database to come back online.

Most apps that maintain a connection pool (like ActiveRecord in Rails) can just open a new connection to the database. However, in some cases an app won't be able to reconnect. If that happens, you can heroku restart your app to bring it back online.

This is one of the reasons we recommend against running hobby databases for critical production applications. Standard and Premium databases include notifications for downtime events, and are much more performant and stable in general. You can use pg:copy to migrate to a standard or premium plan.

If this continues, you can try provisioning a new database (on a different server) with heroku addons:add, then use pg:copy to move the data. Keep in mind that hobby tier rules apply to the $9 basic plan as well as the free database.

Thanks, Bradley

MySQL - count total number of rows in php

<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>

Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I had the same issue today.While searching here for solution,I have did silly mistake that is instead of importing

import org.springframework.transaction.annotation.Transactional;

unknowingly i have imported

import javax.transaction.Transactional;

Afer changing it everything worked fine.

So thought of sharing,If somebody does same mistake .

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

How can I access my localhost from my Android device?

Run CMD as administrator

and on CMD screen type ipconfig and the screen will appear with text

as this photo enter image description here

and you can access your localhost using this ip you have to be connected to same network as your pc connected to

What is an MvcHtmlString and when should I use it?

You would use an MvcHtmlString if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.

Refresh Fragment at reload

you can refresh your fragment when it is visible to user, just add this code into your Fragment this will refresh your fragment when it is visible.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // Refresh your fragment here          
  getFragmentManager().beginTransaction().detach(this).attach(this).commit();
        Log.i("IsRefresh", "Yes");
    }
}

High-precision clock in Python

time.clock() has 13 decimal points on Windows but only two on Linux. time.time() has 17 decimals on Linux and 16 on Windows but the actual precision is different.

I don't agree with the documentation that time.clock() should be used for benchmarking on Unix/Linux. It is not precise enough, so what timer to use depends on operating system.

On Linux, the time resolution is high in time.time():

>>> time.time(), time.time()
(1281384913.4374139, 1281384913.4374161)

On Windows, however the time function seems to use the last called number:

>>> time.time()-int(time.time()), time.time()-int(time.time()), time.time()-time.time()
(0.9570000171661377, 0.9570000171661377, 0.0)

Even if I write the calls on different lines in Windows it still returns the same value so the real precision is lower.

So in serious measurements a platform check (import platform, platform.system()) has to be done in order to determine whether to use time.clock() or time.time().

(Tested on Windows 7 and Ubuntu 9.10 with python 2.6 and 3.1)

Create a file if it doesn't exist

First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition. You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.

That said, you can do it as That One Random Scrub proposed, using try: ... except:. Actually that is the proposed way, according to the python motto "It's easier to ask for forgiveness than permission".

But you can also easily test for existence:

import os
# open file for reading
fn = raw_input("Enter file to open: ")
if os.path.exists(fn):
    fh = open(fn, "r")
else:
    fh = open(fn, "w")

Note: use raw_input() instead of input(), because input() will try to execute the entered text. If you accidently want to test for file "import", you'd get a SyntaxError.

How to show android checkbox at right side?

I can't think of a way with the styling, but you could just set the text of the checkbox to nothing, and put a TextView to the left of the checkbox with your desired text.

Concatenating two std::vectors

You should use vector::insert

v1.insert(v1.end(), v2.begin(), v2.end());

Remove trailing newline from the elements of a string list

If you need to remove just trailing whitespace, you could use str.rstrip(), which should be slightly more efficient than str.strip():

>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']

Changing background colour of tr element on mouseover

tr:hover td {background-color:#000;}

matplotlib savefig() plots different from show()

Old question, but apparently Google likes it so I thought I put an answer down here after some research about this problem.

If you create a figure from scratch you can give it a size option while creation:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(3, 6))

plt.plot(range(10)) #plot example
plt.show() #for control

fig.savefig('temp.png', dpi=fig.dpi)

figsize(width,height) adjusts the absolute dimension of your plot and helps to make sure both plots look the same.

As stated in another answer the dpi option affects the relative size of the text and width of the stroke on lines, etc. Using the option dpi=fig.dpi makes sure the relative size of those are the same both for show() and savefig().

Alternatively the figure size can be changed after creation with:

fig.set_size_inches(3, 6, forward=True)

forward allows to change the size on the fly.

If you have trouble with too large borders in the created image you can adjust those either with:

plt.tight_layout()
#or:
plt.tight_layout(pad=2)

or:

fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight')
#or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight', pad_inches=0.5)

The first option just minimizes the layout and borders and the second option allows to manually adjust the borders a bit. These tips helped at least me to solve my problem of different savefig() and show() images.

How to open a new tab using Selenium WebDriver

The below code will open the link in a new window:

String selectAll = Keys.chord(Keys.SHIFT, Keys.RETURN);
driver.findElement(By.linkText("linkname")).sendKeys(selectAll);

jQuery: Return data after ajax call success

Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.

You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:

If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.

Generally, instead of:

function testAjax() {
  $.ajax({
    url: "getvalue.php",  
    success: function(data) {
      return data; 
    }
  });
}

you can write your testAjax function like this:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

Then you can get your promise like this:

var promise = testAjax();

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:

promise.success(function (data) {
  alert(data);
});

(See updates below for simplified syntax.)

If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.

The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.

See this DEMO.

UPDATE (2015)

Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.

However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.

What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.

But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.

In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.

For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.

How to return a real promise

The function from my example above:

function testAjax() {
  return $.ajax({
      url: "getvalue.php"
  });
}

returns a jqXHR object, which is a jQuery Deferred Object.

To make it return a real promise, you can change it to - using the method from the Q wiki:

function testAjax() {
  return Q($.ajax({
      url: "getvalue.php"
  }));
}

or, using the method from the HTML5 Rocks article:

function testAjax() {
  return Promise.resolve($.ajax({
      url: "getvalue.php"
  }));
}

This Promise.resolve($.ajax(...)) is also what is explained in the promise module documentation and it should work with ES6 Promise.resolve().

To use the ES6 Promises today you can use es6-promise module's polyfill() by Jake Archibald.

To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.

For more info see:

Future of jQuery

Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.

Interesting talks

UPDATE (2016)

There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.

Using the jQuery API, instead of:

promise.success(function (data) {
  alert(data);
});

you can write:

promise.success(data => alert(data));

or using the Promises/A+ API:

promise.then(data => alert(data));

Remember to always use rejection handlers either with:

promise.then(data => alert(data), error => alert(error));

or with:

promise.then(data => alert(data)).catch(error => alert(error));

See this answer to see why you should always use rejection handlers with promises:

Of course in this example you could use just promise.then(alert) because you're just calling alert with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:

promise.then(data => alert("x is " + data.x));

Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).

For the support of arrow functions, see:

UPDATE (2017)

There is an even newer syntax right now called async functions with a new await keyword that instead of this code:

functionReturningPromise()
    .then(data => console.log('Data:', data))
    .catch(error => console.log('Error:', error));

lets you write:

try {
    let data = await functionReturningPromise();
    console.log('Data:', data);
} catch (error) {
    console.log('Error:', error);
}

You can only use it inside of a function created with the async keyword. For more info, see:

For support in browsers, see:

For support in Node, see:

In places where you don't have native support for async and await you can use Babel:

or with a slightly different syntax a generator based approach like in co or Bluebird coroutines:

More info

Some other questions about promises for more details:

Get full query string in C# ASP.NET

This should work fine for you.

Write this code in the Page_Load event of the page.

string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);

MySQL: Grant **all** privileges on database

Hello I used this code to have the super user in mysql

GRANT EXECUTE, PROCESS, SELECT, SHOW DATABASES, SHOW VIEW, ALTER, ALTER ROUTINE,
    CREATE, CREATE ROUTINE, CREATE TEMPORARY TABLES, CREATE VIEW, DELETE, DROP,
    EVENT, INDEX, INSERT, REFERENCES, TRIGGER, UPDATE, CREATE USER, FILE,
    LOCK TABLES, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHUTDOWN,
    SUPER
        ON *.* TO mysql@'%'
    WITH GRANT OPTION;

and then

FLUSH PRIVILEGES;

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

initializing a boolean array in java

The array will be initialized to false when you allocate it.

All arrays in Java are initialized to the default value for the type. This means that arrays of ints are initialised to 0, arrays of booleans are initialised to false and arrays of reference types are initialised to null.

How to set placeholder value using CSS?

AFAIK, you can't do it with CSS alone. CSS has content rule but even that can be used to insert content before or after an element using pseudo selectors. You need to resort to javascript for that OR use placeholder attribute if you are using HTML5 as pointed out by @Blender.

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

Convert/cast an stdClass object to another class

See the manual on Type Juggling on possible casts.

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

You would have to write a Mapper that does the casting from stdClass to another concrete class. Shouldn't be too hard to do.

Or, if you are in a hackish mood, you could adapt the following code:

function arrayToObject(array $array, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(serialize($array), ':')
    ));
}

which pseudocasts an array to an object of a certain class. This works by first serializing the array and then changing the serialized data so that it represents a certain class. The result is unserialized to an instance of this class then. But like I said, it's hackish, so expect side-effects.

For object to object, the code would be

function objectToObject($instance, $className) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($className),
        $className,
        strstr(strstr(serialize($instance), '"'), ':')
    ));
}

What is the difference between varchar and nvarchar?

I have to say here (I realise that I'm probably going to open myself up to a slating!), but surely the only time when NVARCHAR is actually more useful (notice the more there!) than VARCHAR is when all of the collations on all of the dependant systems and within the database itself are the same...? If not then collation conversion has to happen anyway and so makes VARCHAR just as viable as NVARCHAR.

To add to this, some database systems, such as SQL Server (before 2012) have a page size of approx. 8K. So, if you're looking at storing searchable data not held in something like a TEXT or NTEXT field then VARCHAR provides the full 8k's worth of space whereas NVARCHAR only provides 4k (double the bytes, double the space).

I suppose, to summarise, the use of either is dependent on:

  • Project or context
  • Infrastructure
  • Database system

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

You're saying that you need GPS location first if its available, but what you did is first you're getting location from network provider and then from GPS. This will get location from Network and GPS as well if both are available. What you can do is, write these cases in if..else if block. Similar to-

if( !isGPSEnabled && !isNetworkEnabled) {

// Can't get location by any way

} else {

    if(isGPSEnabled) {

    // get location from GPS

    } else if(isNetworkEnabled) {

    // get location from Network Provider

    }
}

So this will fetch location from GPS first (if available), else it will try to fetch location from Network Provider.

EDIT:

To make it better, I'll post a snippet. Consider it is in try-catch:

boolean gps_enabled = false;
boolean network_enabled = false;

LocationManager lm = (LocationManager) mCtx
                .getSystemService(Context.LOCATION_SERVICE);

gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location net_loc = null, gps_loc = null, finalLoc = null;

if (gps_enabled)
    gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
    net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if (gps_loc != null && net_loc != null) {

    //smaller the number more accurate result will
    if (gps_loc.getAccuracy() > net_loc.getAccuracy()) 
        finalLoc = net_loc;
    else
        finalLoc = gps_loc;

        // I used this just to get an idea (if both avail, its upto you which you want to take as I've taken location with more accuracy)

} else {

    if (gps_loc != null) {
        finalLoc = gps_loc;
    } else if (net_loc != null) {
        finalLoc = net_loc;
    }
}

Now you check finalLoc for null, if not then return it. You can write above code in a function which returns the desired (finalLoc) location. I think this might help.

HTTP test server accepting GET/POST requests

Create choose a free web host and put the following code

 <h1>Request Headers</h1>
 <?php
 $headers = apache_request_headers();

 foreach ($headers as $header => $value) {
     echo "<b>$header:</b> $value <br />\n";
 }
 ?>

Error inflating class android.support.v7.widget.Toolbar?

Please read this Google Blog post: http://android-developers.blogspot.com/2014/10/appcompat-v21-material-design-for-pre.html

<android.support.v7.widget.Toolbar
    android:id="@+id/my_awesome_toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary" />

Also, you are giving it the same "ID" twice, please remove the "id" from your include:

<include android:id="@+id/toolbar" layout="@layout/toolbar" />

Change the background color in a twitter bootstrap modal?

If you want to change the background color of the backdrop for a specific modal, you can access the backdrop element in this way:

$('#myModal').data('bs.modal').$backdrop

Then you can change any css property via .css jquery function. In particular, with background:

$('#myModal').data('bs.modal').$backdrop.css('background-color','orange')

Note that $('#myModal') has to be initialized, otherwise $backdrop is going to be null. Same applies to bs.modal data element.

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

After you install redis, type from terminal:

redis-server

and you'll have redis running

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

enter the values as 0:mm:ss and format as [m]:ss

as this is now in the mins & seconds, simple arithmetic will allow you to calculate your statistics

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

Use string in switch case in java

Everybody is using at least Java 7 now, right? Here is the answer to the original problem:

String myString = getFruitString();

switch (myString) {

    case "apple":
        method1();
        break;

    case "carrot":
        method2();
        break;

    case "mango":
        method3();
        break;

    case "orange":
        method4();
        break;
}

Notes

  • The case statements are equivalent to using String.equals.
  • As usual, String matching is case sensitive.
  • According to the docs, this is generally faster than using chained if-else statements (as in cHao's answer).

How to build x86 and/or x64 on Windows from command line with CMAKE?

Besides CMAKE_GENERATOR_PLATFORM variable, there is also the -A switch

cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64

https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection

  -A <platform-name>           = Specify platform name if supported by
                                 generator.

How to convert FileInputStream to InputStream?

FileInputStream is an inputStream.

FileInputStream fis = new FileInputStream("c://filename");
InputStream is = fis;
fis.close();  
return is;

Of course, this will not do what you want it to do; the stream you return has already been closed. Just return the FileInputStream and be done with it. The calling code should close it.

Open Sublime Text from Terminal in macOS

You can just add an alias

alias subl='/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl'

Then you should be able to open a folder or whatever with

subl <path>

How to stop mysqld

I did it with next command:

sudo killall mysqld

How can I split and parse a string in Python?

If it's always going to be an even LHS/RHS split, you can also use the partition method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS) if the separator is found, and (original_string, '', '') if the separator wasn't present:

>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')

>>> "shazam".partition("_")
('shazam', '', '')

Replace a string in shell script using a variable

If you want to interpret $replace, you should not use single quotes since they prevent variable substitution.

Try:

echo $LINE | sed -e "s/12345678/${replace}/g"

Transcript:

pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _

Just be careful to ensure that ${replace} doesn't have any characters of significance to sed (like / for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.

CSS3 :unchecked pseudo-class

I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.

input[type="checkbox"] {
  // Unchecked Styles
}
input[type="checkbox"]:checked {
  // Checked Styles
}

I apologize for bringing up an old thread but felt like it could have used a better answer.

EDIT (3/3/2016):

W3C Specs state that :not(:checked) as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"] selector. See example below for clarification.

input[type="checkbox"] {
  /* Base Styles aka unchecked */
  font-weight: 300; // Will be overwritten by :checked
  font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
  /* Explicit Unchecked Styles */
  border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
  /* Checked Styles */
  font-weight: 900; // Use a bold font when checked
}

Without using :not(:checked) in the example above the :checked selector would have needed to use a border: none; to achieve the same affect.

Use the input[type="checkbox"] for base styling to reduce duplication.

Use the input[type="checkbox"]:not(:checked) for explicit unchecked styles that you do not want to apply to the checked state.

Angularjs loading screen on ajax request

In reference of this answer

https://stackoverflow.com/a/17144634/4146239

For me is the best solution but there's a way to avoid use jQuery.

_x000D_
_x000D_
.directive('loading', function () {_x000D_
      return {_x000D_
        restrict: 'E',_x000D_
        replace:true,_x000D_
        template: '<div class="loading"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" width="20" height="20" />LOADING...</div>',_x000D_
        link: function (scope, element, attr) {_x000D_
              scope.$watch('loading', function (val) {_x000D_
                  if (val)_x000D_
                      scope.loadingStatus = 'true';_x000D_
                  else_x000D_
                      scope.loadingStatus = 'false';_x000D_
              });_x000D_
        }_x000D_
      }_x000D_
  })_x000D_
_x000D_
  .controller('myController', function($scope, $http) {_x000D_
      $scope.cars = [];_x000D_
      _x000D_
      $scope.clickMe = function() {_x000D_
        scope.loadingStatus = 'true'_x000D_
        $http.get('test.json')_x000D_
          .success(function(data) {_x000D_
            $scope.cars = data[0].cars;_x000D_
            $scope.loadingStatus = 'false';_x000D_
        });_x000D_
      }_x000D_
      _x000D_
  });
_x000D_
<body ng-app="myApp" ng-controller="myController" ng-init="loadingStatus='true'">_x000D_
        <loading ng-show="loadingStatus" ></loading>_x000D_
  _x000D_
        <div ng-repeat="car in cars">_x000D_
          <li>{{car.name}}</li>_x000D_
        </div>_x000D_
        <button ng-click="clickMe()" class="btn btn-primary">CLICK ME</button>_x000D_
  _x000D_
</body>
_x000D_
_x000D_
_x000D_

You need to replace $(element).show(); and (element).show(); with $scope.loadingStatus = 'true'; and $scope.loadingStatus = 'false';

Than, you need to use this variable to set the ng-show attribute of the element.

Convert Pandas DataFrame to JSON format

Try this one:

json.dumps(json.loads(df.to_json(orient="records")))

Increasing Google Chrome's max-connections-per-server limit to more than 6

IE is even worse with 2 connection per domain limit. But I wouldn't rely on fixing client browsers. Even if you have control over them, browsers like chrome will auto update and a future release might behave differently than you expect. I'd focus on solving the problem within your system design.

Your choices are to:

  1. Load the images in sequence so that only 1 or 2 XHR calls are active at a time (use the success event from the previous image to check if there are more images to download and start the next request).

  2. Use sub-domains like serverA.myphotoserver.com and serverB.myphotoserver.com. Each sub domain will have its own pool for connection limits. This means you could have 2 requests going to 5 different sub-domains if you wanted to. The downfall is that the photos will be cached according to these sub-domains. BTW, these don't need to be "mirror" domains, you can just make additional DNS pointers to the exact same website/server. This means you don't have the headache of administrating many servers, just one server with many DNS records.

Can you target <br /> with css?

I placed a <br> tag into a <span> tag and was able to use display:none; on the <span> to control when not to use the <br> tag using Media Queries.

No grammar constraints (DTD or XML schema) detected for the document

What I found to be the solution was something very very simple that I think you should try before tinkering with the preferences. In my case I had this problem in a strings file that had as a base tag "resources" ...all I did was delete the tag from the top and the bottom, clean the project, save the file and reinsert the tag. The problem has since disappeared and never gave me any warnings. It may sound to simple to be true but hey, sometimes it's the simplest things that solve the problems. Cheers

Options for HTML scraping?

I like Google Spreadsheets' ImportXML(URL, XPath) function.

It will repeat cells down the column if your XPath expression returns more than one value.

You can have up to 50 importxml() functions on one spreadsheet.

RapidMiner's Web Plugin is also pretty easy to use. It can do posts, accepts cookies, and can set the user-agent.

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

Execute a file with arguments in Python shell

For more interesting scenarios, you could also look at the runpy module. Since python 2.7, it has the run_path function. E.g:

import runpy
import sys

# argv[0] will be replaced by runpy
# You could also skip this if you get sys.argv populated
# via other means
sys.argv = ['', 'arg1' 'arg2']
runpy.run_path('./abc.py', run_name='__main__')

Get the number of rows in a HTML table

Well it depends on what you have in your table.

its one of the following If you have only one table

var count = $('#gvPerformanceResult tr').length;

If you are concerned about sub tables but this wont work with tbody and thead (if you use them)

var count = $('#gvPerformanceResult>tr').length;

Where by this will work (but is quite frankly overkill.)

var count = $('#gvPerformanceResult>tbody>tr').length;

How to install mcrypt extension in xampp

First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
  yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

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

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

Temporarily disable all foreign key constraints

Truncating the table wont be possible even if you disable the foreign keys.so you can use delete command to remove all the records from the table,but be aware if you are using delete command for a table which consists of millions of records then your package will be slow and your transaction log size will increase and it may fill up your valuable disk space.

If you drop the constraints it may happen that you will fill up your table with unclean data and when you try to recreate the constraints it may not allow you to as it will give errors. so make sure that if you drop the constraints,you are loading data which are correctly related to each other and satisfy the constraint relations which you are going to recreate.

so please carefully think the pros and cons of each method and use it according to your requirements

Show/hide forms using buttons and JavaScript

There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

_x000D_
_x000D_
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
    document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
    stuff hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

How to search by key=>value in a multidimensional array in PHP

if (isset($array[$key]) && $array[$key] == $value)

A minor imporvement to the fast version.

Extract substring in Bash

A bash solution:

IFS="_" read -r x digs x <<<'someletters_12345_moreleters.ext'

This will clobber a variable called x. The var x could be changed to the var _.

input='someletters_12345_moreleters.ext'
IFS="_" read -r _ digs _ <<<"$input"

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.

What is SaaS, PaaS and IaaS? With examples

IaaS (Infra as a Service)

IaaS provides the infrastructure such as virtual machines and other resources like virtual-machine disk image library, block and file-based storage, firewalls, load balancers, IP addresses, virtual local area networks etc. Infrastructure as service or IaaS is the basic layer in cloud computing model.

Common examples: DigitalOcean, Linode, Rackspace, Amazon Web Services (AWS), Cisco Metapod, Microsoft Azure, Google Compute Engine (GCE) are some popular examples of Iaas.

PaaS (Platform as a Service)

PaaS or platform as a service model provides you computing platforms which typically includes an operating system, programming language execution environment, database, web server. technically It is a layer on top of IaaS as the second thing you demand after Infrastructure is a platform.

Common examples: AWS Elastic Beanstalk, Windows Azure, Heroku, Force.com, Google App Engine, Apache Stratos.

SaaS (Software as a Service)

In a SaaS, you are provided access to application services installed at a server. You don’t have to worry about installation, maintenance or coding of that software. You can access and operate the software with just your browser. You don’t have to download or install any kind of setup or OS, the software is just available for you to access and operate. The software maintenance or setup or help will be provided by SaaS provider company and you will only have to pay for your usage.

Common examples: Google Apps, Microsoft office365, Google docs, Gmail, WHMCS billing software

Basic difference between IaaS, PaaS & SaaS enter image description here enter image description here

Programmatically navigate to another view controller/scene

If you want to navigate to Controller created Programmatically, then do this:

let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)

If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
        self.present(newViewController, animated: true, completion: nil)

How to round double to nearest whole number and then convert to a float?

float b = (float)Math.ceil(a); or float b = (float)Math.round(a);

Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).

Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.

TypeError: 'float' object is not callable

The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

How to block until an event is fired in c#

If you're happy to use the Microsoft Reactive Extensions, then this can work nicely:

public class Foo
{
    public delegate void MyEventHandler(object source, MessageEventArgs args);
    public event MyEventHandler _event;
    public string ReadLine()
    {
        return Observable
            .FromEventPattern<MyEventHandler, MessageEventArgs>(
                h => this._event += h,
                h => this._event -= h)
            .Select(ep => ep.EventArgs.Message)
            .First();
    }
    public void SendLine(string message)
    {
        _event(this, new MessageEventArgs() { Message = message });
    }
}

public class MessageEventArgs : EventArgs
{
    public string Message;
}

I can use it like this:

var foo = new Foo();

ThreadPoolScheduler.Instance
    .Schedule(
        TimeSpan.FromSeconds(5.0),
        () => foo.SendLine("Bar!"));

var resp = foo.ReadLine();

Console.WriteLine(resp);

I needed to call the SendLine message on a different thread to avoid locking, but this code shows that it works as expected.

Jquery Ajax, return success/error from mvc.net controller

 $.ajax({
    type: "POST",
    data: formData,
    url: "/Forms/GetJobData",
    dataType: 'json',
    contentType: false,
    processData: false,               
    success: function (response) {
        if (response.success) {
            alert(response.responseText);
        } else {
            // DoSomethingElse()
            alert(response.responseText);
        }                          
    },
    error: function (response) {
        alert("error!");  // 
    }

});

Controller:

[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
    var mimeType = jobData.File.ContentType;
    var isFileSupported = IsFileSupported(mimeType);

    if (!isFileSupported){        
         //  Send "false"
        return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        //  Send "Success"
        return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
    }   
}

---Supplement:---

basically you can send multiple parameters this way:

Controller:

 return Json(new { 
                success = true,
                Name = model.Name,
                Phone = model.Phone,
                Email = model.Email                                
            }, 
            JsonRequestBehavior.AllowGet);

Html:

<script> 
     $.ajax({
                type: "POST",
                url: '@Url.Action("GetData")',
                contentType: 'application/json; charset=utf-8',            
                success: function (response) {

                   if(response.success){ 
                      console.log(response.Name);
                      console.log(response.Phone);
                      console.log(response.Email);
                    }


                },
                error: function (response) {
                    alert("error!"); 
                }
            });

How to play a sound using Swift?

Swift 4, 4.2 and 5

Play audio from URL and from your project (Local File)

import UIKit
import AVFoundation

class ViewController: UIViewController{

var audioPlayer : AVPlayer!

override func viewDidLoad() {
        super.viewDidLoad()
// call what ever function you want.
    }

    private func playAudioFromURL() {
        guard let url = URL(string: "https://geekanddummy.com/wp-content/uploads/2014/01/coin-spin-light.mp3") else {
            print("error to get the mp3 file")
            return
        }
        do {
            audioPlayer = try AVPlayer(url: url as URL)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

    private func playAudioFromProject() {
        guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else {
            print("error to get the mp3 file")
            return
        }

        do {
            audioPlayer = try AVPlayer(url: url)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

}

MySQL Error 1264: out of range value for column

You can also change the data type to bigInt and it will solve your problem, it's not a good practice to keep integers as strings unless needed. :)

ALTER TABLE T_PERSON MODIFY mobile_no BIGINT;

Batch file include external file for variables

Note: I'm assuming Windows batch files as most people seem to be unaware that there are significant differences and just blindly call everything with grey text on black background DOS. Nevertheless, the first variant should work in DOS as well.

Executable configuration

The easiest way to do this is to just put the variables in a batch file themselves, each with its own set statement:

set var1=value1
set var2=value2
...

and in your main batch:

call config.cmd

Of course, that also enables variables to be created conditionally or depending on aspects of the system, so it's pretty versatile. However, arbitrary code can run there and if there is a syntax error, then your main batch will exit too. In the UNIX world this seems to be fairly common, especially for shells. And if you think about it, autoexec.bat is nothing else.

Key/value pairs

Another way would be some kind of var=value pairs in the configuration file:

var1=value1
var2=value2
...

You can then use the following snippet to load them:

for /f "delims=" %%x in (config.txt) do (set "%%x")

This utilizes a similar trick as before, namely just using set on each line. The quotes are there to escape things like <, >, &, |. However, they will themselves break when quotes are used in the input. Also you always need to be careful when further processing data in variables stored with such characters.

Generally, automatically escaping arbitrary input to cause no headaches or problems in batch files seems pretty impossible to me. At least I didn't find a way to do so yet. Of course, with the first solution you're pushing that responsibility to the one writing the config file.

How to compare two floating point numbers in Bash?

bash handles only integer maths but you can use bc command as follows:

$ num1=3.17648E-22
$ num2=1.5
$ echo $num1'>'$num2 | bc -l
0
$ echo $num2'>'$num1 | bc -l
1

Note that exponent sign must be uppercase

Git command to display HEAD commit id?

You can use

git log -g branchname

to see git reflog information formatted like the git log output

Uploading/Displaying Images in MVC 4

        <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }

MySQL Workbench Edit Table Data is read only

This is the Known limitation in MySQLWorkbench (you can't edit table w/o PK):

To Edit the Table:

Method 1: (method not working in somecases)
right-click on a table within the Object Browser and choose the Edit Table Data option from there.

Method 2:
I would rather suggest you to add Primary Key Instead:

ALTER TABLE `your_table_name` ADD PRIMARY KEY (`column_name`);

and you might want to remove the existing rows first:

Truncate table your_table_name

How to parse a JSON object to a TypeScript Object

you can make a new object of your class and then assign it's parameters dynamically from the JSON object's parameters.

const employeeData = JSON.parse(employeeString);
let emp:Employee=new Employee();
const keys=Object.keys(employeeData);
keys.forEach(key=>{
    emp[key]=employeeData[key];
});
console.log(emp);

now the emp is an object of Employee containing all fields of employeeString's Json object(employeeData);

TypeError: not all arguments converted during string formatting python

For me, as I was storing many values within a single print call, the solution was to create a separate variable to store the data as a tuple and then call the print function.

x = (f"{id}", f"{name}", f"{age}")
print(x) 

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

Textarea Auto height

This using Pure JavaScript Code.

_x000D_
_x000D_
function auto_grow(element) {_x000D_
    element.style.height = "5px";_x000D_
    element.style.height = (element.scrollHeight)+"px";_x000D_
}
_x000D_
textarea {_x000D_
    resize: none;_x000D_
    overflow: hidden;_x000D_
    min-height: 50px;_x000D_
    max-height: 100px;_x000D_
}
_x000D_
<textarea oninput="auto_grow(this)"></textarea>
_x000D_
_x000D_
_x000D_

ASP.NET MVC Conditional validation

Typical usage for conditional removal of error from Model State:

  1. Make conditional first part of controller action
  2. Perform logic to remove error from ModelState
  3. Do the rest of the existing logic (typically Model State validation, then everything else)

Example:

public ActionResult MyAction(MyViewModel vm)
{
    // perform conditional test
    // if true, then remove from ModelState (e.g. ModelState.Remove("MyKey")

    // Do typical model state validation, inside following if:
    //     if (!ModelState.IsValid)

    // Do rest of logic (e.g. fetching, saving

In your example, keep everything as is and add the logic suggested to your Controller's Action. I'm assuming your ViewModel passed to the controller action has the Person and Senior Person objects with data populated in them from the UI.

How to copy from CSV file to PostgreSQL table with headers in CSV file?

I have been using this function for a while with no problems. You just need to provide the number columns there are in the csv file, and it will take the header names from the first row and create the table for you:

create or replace function data.load_csv_file
    (
        target_table  text, -- name of the table that will be created
        csv_file_path text,
        col_count     integer
    )

    returns void

as $$

declare
    iter      integer; -- dummy integer to iterate columns with
    col       text; -- to keep column names in each iteration
    col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet

begin
    set schema 'data';

    create table temp_table ();

    -- add just enough number of columns
    for iter in 1..col_count
    loop
        execute format ('alter table temp_table add column col_%s text;', iter);
    end loop;

    -- copy the data from csv file
    execute format ('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_file_path);

    iter := 1;
    col_first := (select col_1
                  from temp_table
                  limit 1);

    -- update the column names based on the first row which has the column names
    for col in execute format ('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first)
    loop
        execute format ('alter table temp_table rename column col_%s to %s', iter, col);
        iter := iter + 1;
    end loop;

    -- delete the columns row // using quote_ident or %I does not work here!?
    execute format ('delete from temp_table where %s = %L', col_first, col_first);

    -- change the temp table name to the name given as parameter, if not blank
    if length (target_table) > 0 then
        execute format ('alter table temp_table rename to %I', target_table);
    end if;
end;

$$ language plpgsql;

How to get the primary IP address of the local machine on Linux and OS X?

Assuming you need your primary public IP as it seen from the rest of the world, try any of those:

wget http://ipecho.net/plain -O - -q
curl http://icanhazip.com
curl http://ifconfig.me/ip

Angular 2 Dropdown Options Default Value

Add binding property selected, but make sure to make it null, for other fields e.g:

<option *ngFor="#workout of workouts" [selected]="workout.name =='back' ? true: null">{{workout.name}}</option>

Now it will work

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had this issue when having a custom display in my terminal when creating a new git project (I have my branch display before the pathname e.g. :/current/path). All I needed to do was do my initial commit to my master branch to get this message to go away.

Insert the same fixed value into multiple rows

The SQL you need is:

Update table set table_column = "test";

The SQL you posted creates a new row rather than updating existing rows.

How to fix missing dependency warning when using useEffect React Hook?

If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning

useEffect(() => {
    const fetchBusinesses = () => {
       return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };
  fetchBusinesses();
}, []);

If however you are using fetchBusinesses outside of render, you must note two things

  1. Is there any issue with you not passing fetchBusinesses as a method when it's used during mount with its enclosing closure?
  2. Does your method depend on some variables which it receives from its enclosing closure? This is not the case for you.
  3. On every render, fetchBusinesses will be re-created and hence passing it to useEffect will cause issues. So first you must memoize fetchBusinesses if you were to pass it to the dependency array.

To sum it up I would say that if you are using fetchBusinesses outside of useEffect you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps otherwise you can move the method inside of useEffect

To disable the rule you would write it like

useEffect(() => {
   // other code
   ...

   // eslint-disable-next-line react-hooks/exhaustive-deps
}, []) 

Reset push notification settings for app

In addition to the answer of ianolito.

Had the same issue with an app I downloaded a year ago and denying push notification initially. Now wanting push notifications back, these steps worked for me on iOS 7 beta. Not sure which point(s) triggered it exactly.

  • Close and delete the app.
  • Go to your iCloud settings and delete the app from the iCloud. Do this on all other devices where you have iCloud backup for apps enabled. After deactivating and deleting make a fresh backup. The app should not be listed any more under the backups. (This is maybe why the Technical Note from Apple described by ianolito stopped working in iOS 5, since iCloud was introduced in iOS 5 and many have iCloud backup for apps enabled.)
  • Go to your time settings and set the time more than 1 month ahead.
  • Switch the iPhone off (no reset).
  • Wait a minute, switch it on again and download the app again.
  • Start the app and I was presented the dialog again.
  • Enable app backup again, since it is still deactivated. Correct the time.

Thank god I did not have to "Erase All Content And Settings". Maybe it will help someone.

How to write JUnit test with Spring Autowire?

In Spring 2.1.5 at least, the XML file can be conveniently replaced by annotations. Piggy backing on @Sembrano's answer, I have this. "Look ma, no XML".

It appears I to had list all the classes I need @Autowired in the @ComponentScan

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(
    basePackageClasses = {
            OwnerService.class
            })
@EnableAutoConfiguration
public class OwnerIntegrationTest {
    
    @Autowired
    OwnerService ownerService;
    
    @Test
    public void testOwnerService() {
       Assert.assertNotNull(ownerService);
    }
}

Passing enum or object through an intent (the best solution)

It may be possible to make your Enum implement Serializable then you can pass it via the Intent, as there is a method for passing it as a serializable. The advice to use int instead of enum is bogus. Enums are used to make your code easier to read and easier to maintain. It would a large step backwards into the dark ages to not be able to use Enums.

Online SQL syntax checker conforming to multiple databases

I am willing to bet some of my reputation that there is no such thing.

Partially because if you are worried about cross-platform SQL compatibility, your best bet in turn is to abstract your database code with some API or ORM tool that handles these things for you, and is well supported, so will deal with newer database versions as they come out.

Exact kind of API available to you will be dependent on your programming language/platform. For example, PHP has Pear:DB and others, I personally have found quite nice Python's ORM features implemented in Django framework. I presume there should be some of these things available on other platforms as well.

jQuery: How can I create a simple overlay?

Here's a fully encapsulated version which adds an overlay (including a share button) to any IMG element where data-photo-overlay='true.

JSFiddle http://jsfiddle.net/wloescher/7y6UX/19/

HTML

<img id="my-photo-id" src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" alt="Photo" data-photo-overlay="true" />

CSS

#photoOverlay {
    background: #ccc;
    background: rgba(0, 0, 0, .5);
    display: none;
    height: 50px;
    left: 0;
    position: absolute;
    text-align: center;
    top: 0;
    width: 50px;
    z-index: 1000;
}

#photoOverlayShare {
    background: #fff;
    border: solid 3px #ccc;
    color: #ff6a00;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    margin-left: auto;
    margin: 15px;
    padding: 5px;
    position: absolute;
    left: calc(100% - 100px);
    text-transform: uppercase;
    width: 50px;
}

JavaScript

(function () {
    // Add photo overlay hover behavior to selected images
    $("img[data-photo-overlay='true']").mouseenter(showPhotoOverlay);

    // Create photo overlay elements
    var _isPhotoOverlayDisplayed = false;
    var _photoId;
    var _photoOverlay = $("<div id='photoOverlay'></div>");
    var _photoOverlayShareButton = $("<div id='photoOverlayShare'>Share</div>");

    // Add photo overlay events
    _photoOverlay.mouseleave(hidePhotoOverlay);
    _photoOverlayShareButton.click(sharePhoto);

    // Add photo overlay elements to document
    _photoOverlay.append(_photoOverlayShareButton);
    _photoOverlay.appendTo(document.body);

    // Show photo overlay
    function showPhotoOverlay(e) {
        // Get sender 
        var sender = $(e.target || e.srcElement);

        // Check to see if overlay is already displayed
        if (!_isPhotoOverlayDisplayed) {
            // Set overlay properties based on sender
            _photoOverlay.width(sender.width());
            _photoOverlay.height(sender.height());

            // Position overlay on top of photo
            if (sender[0].x) {
                _photoOverlay.css("left", sender[0].x + "px");
                _photoOverlay.css("top", sender[0].y) + "px";
            }
            else {
                // Handle IE incompatibility
                _photoOverlay.css("left", sender.offset().left);
                _photoOverlay.css("top", sender.offset().top);
            }

            // Get photo Id
            _photoId = sender.attr("id");

            // Show overlay
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = true;
        }
    }

    // Hide photo overlay
    function hidePhotoOverlay(e) {
        if (_isPhotoOverlayDisplayed) {
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = false;
        }
    }

    // Share photo
    function sharePhoto() {
        alert("TODO: Share photo. [PhotoId = " + _photoId + "]");
        }
    }
)();

Querying DynamoDB by date

Your Hash key (primary of sort) has to be unique (unless you have a range like stated by others).

In your case, to query your table you should have a secondary index.

|  ID  | DataID | Created | Data |
|------+--------+---------+------|
| hash | xxxxx  | 1234567 | blah |

Your Hash Key is ID Your secondary index is defined as: DataID-Created-index (that's the name that DynamoDB will use)

Then, you can make a query like this:

var params = {
    TableName: "Table",
    IndexName: "DataID-Created-index",
    KeyConditionExpression: "DataID = :v_ID AND Created > :v_created",
    ExpressionAttributeValues: {":v_ID": {S: "some_id"},
                                ":v_created": {N: "timestamp"}
    },
    ProjectionExpression: "ID, DataID, Created, Data"
};

ddb.query(params, function(err, data) {
    if (err) 
        console.log(err);
    else {
        data.Items.sort(function(a, b) {
            return parseFloat(a.Created.N) - parseFloat(b.Created.N);
        });
        // More code here
    }
});

Essentially your query looks like:

SELECT * FROM TABLE WHERE DataID = "some_id" AND Created > timestamp;

The secondary Index will increase the read/write capacity units required so you need to consider that. It still is a lot better than doing a scan, which will be costly in reads and in time (and is limited to 100 items I believe).

This may not be the best way of doing it but for someone used to RD (I'm also used to SQL) it's the fastest way to get productive. Since there is no constraints in regards to schema, you can whip up something that works and once you have the bandwidth to work on the most efficient way, you can change things around.

Removing duplicate values from a PowerShell array

Use Select-Object (whose alias is select) with the -Unique switch; e.g.:

$a = @(1,2,3,4,5,5,6,7,8,9,0,0)
$a = $a | select -Unique

How to get featured image of a product in woocommerce

I had the same problem and solved it by using the default woocommerce hook to display the product image.

while ( $loop->have_posts() ) : $loop->the_post();
   echo woocommerce_get_product_thumbnail('woocommerce_full_size');
endwhile;

Available parameters:

  • woocommerce_thumbnail
  • woocommerce_full_size

RadioGroup: How to check programmatically

Grab the radio group and look at the children to see if any are unchecked.

RadioGroup rg = (RadioGroup) view;
int checked = savedInstanceState.getInt(wrap.getAttributeName());

if(checked != -1) {
    RadioButton btn = (RadioButton) rg.getChildAt(checked);
    btn.toggle();
}

How do I make a comment in a Dockerfile?

Format

Here is the format of the Dockerfile:

We can use # for commenting purpose#Comment for example

#FROM microsoft/aspnetcore
FROM microsoft/dotnet
COPY /publish /app
WORKDIR /app
ENTRYPOINT ["dotnet", "WebApp.dll"]

From the above file when we build the docker, it skips the first line and goes to the next line because we have commented it using #

How to generate unique IDs for form labels in React?

You could use a library such as node-uuid for this to make sure you get unique ids.

Install using:

npm install node-uuid --save

Then in your react component add the following:

import {default as UUID} from "node-uuid";
import {default as React} from "react";

export default class MyComponent extends React.Component {   
  componentWillMount() {
    this.id = UUID.v4();
  }, 
  render() {
    return (
      <div>
        <label htmlFor={this.id}>My label</label>
        <input id={this.id} type="text"/>
      </div>
    );
  }   
}

get DATEDIFF excluding weekends using sql server

BEGIN 
DECLARE @totaldays INT; 
DECLARE @weekenddays INT;

SET @totaldays = DATEDIFF(DAY, @startDate, @endDate) 
SET @weekenddays = ((DATEDIFF(WEEK, @startDate, @endDate) * 2) + -- get the number of weekend days in between
                       CASE WHEN DATEPART(WEEKDAY, @startDate) = 1 THEN 1 ELSE 0 END + -- if selection was Sunday, won't add to weekends
                       CASE WHEN DATEPART(WEEKDAY, @endDate) = 6 THEN 1 ELSE 0 END)  -- if selection was Saturday, won't add to weekends

Return (@totaldays - @weekenddays)

END

This is on SQL Server 2014

Delete all data in SQL Server database

EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'

EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'

EXEC sp_MSForEachTable 'DELETE FROM ?'

EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL'

EXEC sp_MSFOREACHTABLE 'SELECT * FROM ?'

GO

Closing Excel Application using VBA

You can try out

ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit

Where does Jenkins store configuration files for the jobs it runs?

The best approach would be to keep your job configurations in a Jenkinsfile that live in source control.

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

How to enable native resolution for apps on iPhone 6 and 6 Plus?

If you are using asset catalogs, go to the LaunchImages asset catalog and add the new launch images for the two new iPhones. You may need to right-click and choose "Add New Launch Image" to see a place to add the new images.

The iPhone 6 (Retina HD 4.7) requires a portrait launch image of 750 x 1334.

The iPhone 6 Plus (Retina HD 5.5) requires both portrait and landscape images sized as 1242 x 2208 and 2208 x 1242 respectively.

'setInterval' vs 'setTimeout'

setInterval fires again and again in intervals, while setTimeout only fires once.

See reference at MDN.

Get the height and width of the browser viewport without scrollbars using jquery?

$(document).ready(function() {

  //calculate the window height & add css properties for height 100%

  wh = $( window ).height();

  ww = $( window ).width();

  $(".targeted-div").css({"height": wh, "width": ww});

});

What is the Swift equivalent to Objective-C's "@synchronized"?

Details

Xcode 8.3.1, Swift 3.1

Task

Read write value from different threads (async).

Code

class AsyncObject<T>:CustomStringConvertible {
    private var _value: T
    public private(set) var dispatchQueueName: String
   
    let dispatchQueue: DispatchQueue
    
    init (value: T, dispatchQueueName: String) {
        _value = value
        self.dispatchQueueName = dispatchQueueName
        dispatchQueue = DispatchQueue(label: dispatchQueueName)
    }
    
    func setValue(with closure: @escaping (_ currentValue: T)->(T) ) {
        dispatchQueue.sync { [weak self] in
            if let _self = self {
                _self._value = closure(_self._value)
            }
        }
    }
    
    func getValue(with closure: @escaping (_ currentValue: T)->() ) {
        dispatchQueue.sync { [weak self] in
            if let _self = self {
                closure(_self._value)
            }
        }
    }
    
    
    var value: T {
        get {
            return dispatchQueue.sync { _value }
        }
        
        set (newValue) {
            dispatchQueue.sync { _value = newValue }
        }
    }

    var description: String {
        return "\(_value)"
    }
}

Usage

print("Single read/write action")
// Use it when when you need to make single action
let obj = AsyncObject<Int>(value: 0, dispatchQueueName: "Dispatch0")
obj.value = 100
let x = obj.value
print(x)

print("Write action in block")
// Use it when when you need to make many action
obj.setValue{ (current) -> (Int) in
    let newValue = current*2
    print("previous: \(current), new: \(newValue)")
    return newValue
}

Full Sample

extension DispatchGroup

extension DispatchGroup {
    
    class func loop(repeatNumber: Int, action: @escaping (_ index: Int)->(), completion: @escaping ()->()) {
        let group = DispatchGroup()
        for index in 0...repeatNumber {
            group.enter()
            DispatchQueue.global(qos: .utility).async {
                action(index)
                group.leave()
            }
        }
        
        group.notify(queue: DispatchQueue.global(qos: .userInitiated)) {
            completion()
        }
    }
}

class ViewController

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //sample1()
        sample2()
    }
    
    func sample1() {
        print("=================================================\nsample with variable")
        
        let obj = AsyncObject<Int>(value: 0, dispatchQueueName: "Dispatch1")
        
        DispatchGroup.loop(repeatNumber: 5, action: { index in
            obj.value = index
        }) {
            print("\(obj.value)")
        }
    }
    
    func sample2() {
        print("\n=================================================\nsample with array")
        let arr = AsyncObject<[Int]>(value: [], dispatchQueueName: "Dispatch2")
        DispatchGroup.loop(repeatNumber: 15, action: { index in
            arr.setValue{ (current) -> ([Int]) in
                var array = current
                array.append(index*index)
                print("index: \(index), value \(array[array.count-1])")
                return array
            }
        }) {
            print("\(arr.value)")
        }
    }
}

C - reading command line parameters

There's also a C standard built-in library to get command line arguments: getopt

You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

multiprocessing.Pool: When to use apply, apply_async or map?

Here is an overview in a table format in order to show the differences between Pool.apply, Pool.apply_async, Pool.map and Pool.map_async. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:

                  | Multi-args   Concurrence    Blocking     Ordered-results
---------------------------------------------------------------------
Pool.map          | no           yes            yes          yes
Pool.map_async    | no           yes            no           yes
Pool.apply        | yes          no             yes          no
Pool.apply_async  | yes          yes            no           no
Pool.starmap      | yes          yes            yes          yes
Pool.starmap_async| yes          yes            no           no

Notes:

  • Pool.imap and Pool.imap_async – lazier version of map and map_async.

  • Pool.starmap method, very much similar to map method besides it acceptance of multiple arguments.

  • Async methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.

  • Pool.map(or Pool.apply)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.

Examples:

map

Is called for a list of jobs in one time

results = pool.map(func, [1, 2, 3])

apply

Can only be called for one job

for x, y in [[1, 1], [2, 2]]:
    results.append(pool.apply(func, (x, y)))

def collect_result(result):
    results.append(result)

map_async

Is called for a list of jobs in one time

pool.map_async(func, jobs, callback=collect_result)

apply_async

Can only be called for one job and executes a job in the background in parallel

for x, y in [[1, 1], [2, 2]]:
    pool.apply_async(worker, (x, y), callback=collect_result)

starmap

Is a variant of pool.map which support multiple arguments

pool.starmap(func, [(1, 1), (2, 1), (3, 1)])

starmap_async

A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.

pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)

Reference:

Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html

Use '=' or LIKE to compare strings in SQL?

In my small experience:

"=" for Exact Matches.

"LIKE" for Partial Matches.

What's the safest way to iterate through the keys of a Perl hash?

I may get bitten by this one but I think that it's personal preference. I can't find any reference in the docs to each() being different than keys() or values() (other than the obvious "they return different things" answer. In fact the docs state the use the same iterator and they all return actual list values instead of copies of them, and that modifying the hash while iterating over it using any call is bad.

All that said, I almost always use keys() because to me it is usually more self documenting to access the key's value via the hash itself. I occasionally use values() when the value is a reference to a large structure and the key to the hash was already stored in the structure, at which point the key is redundant and I don't need it. I think I've used each() 2 times in 10 years of Perl programming and it was probably the wrong choice both times =)

How to iterate over a TreeMap?

Using Google Collections, assuming K is your key type:

Maps.filterKeys(treeMap, new Predicate<K>() {
  @Override
  public boolean apply(K key) {
    return false; //return true here if you need the entry to be in your new map
  }});

You can use filterEntries instead if you need the value as well.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

My solotion for responsive/dropdown navbar with angular-ui bootstrap (when update to angular 1.5 and, ui-bootrap 1.2.1)
index.html

     ...    
    <link rel="stylesheet" href="/css/app.css">
</head>
<body>


<nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <input type="checkbox" id="navbar-toggle-cbox">
            <div class="navbar-header">
                <label for="navbar-toggle-cbox" class="navbar-toggle" 
                       ng-init="navCollapsed = true" 
                       ng-click="navCollapsed = !navCollapsed"  
                       aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </label>
                <a class="navbar-brand" href="#">Project name</a>
                 <div id="navbar" class="collapse navbar-collapse"  ng-class="{'in':!navCollapsed}">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="/view1">Home</a></li>
                        <li><a href="/view2">About</a></li>
                        <li><a href="#">Contact</a></li>
                        <li uib-dropdown>
                            <a href="#" uib-dropdown-toggle>Dropdown <b class="caret"></b></a>
                            <ul uib-dropdown-menu role="menu" aria-labelledby="split-button">
                                <li role="menuitem"><a href="#">Action</a></li>
                                <li role="menuitem"><a href="#">Another action</a></li>                                   
                            </ul>
                        </li>

                    </ul>
                 </div>
            </div>
        </div>
    </nav>

app.css

/* show the collapse when navbar toggle is checked */
#navbar-toggle-cbox:checked ~ .collapse {
    display: block;
}

/* the checkbox used only internally; don't display it */
#navbar-toggle-cbox {
  display:none
}

How do I enable TODO/FIXME/XXX task tags in Eclipse?

I'm using Eclipse Classic 3.7.1.

The solution is: Window > Preferences > General > Editors > Sctructured Text Editors > Task Tags and checking "Enable searching for Task Tags" checkbox.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I was receiving this error CastError: Cast to ObjectId failed for value “[object Object]” at path “_id” after creating a schema, then modifying it and couldn't track it down. I deleted all the documents in the collection and I could add 1 object but not a second. I ended up deleting the collection in Mongo and that worked as Mongoose recreated the collection.

Is there a kind of Firebug or JavaScript console debug for Android?

You can try YConsole a js embedded console. It is lightweight and simple to use.

  • Catch logs and errors.
  • Object editor.

How to use :

<script type="text/javascript" src="js/YConsole-compiled.js"></script>
<script type="text/javascript" >YConsole.show();</script>

Laravel: How to Get Current Route Name? (v5 ... v7)

I have used for getting route name in larvel 5.3

Request::path()

How might I force a floating DIV to match the height of another floating DIV?

Here is a jQuery plugin to set the heights of multiple divs to be the same. And below is the actual code of the plugin.

$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
    if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
        });
    if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
    if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
        $(this).children().css({'min-height': currentTallest}); 
    });
    return this;
};

Dealing with commas in a CSV file

If you're interested in a more educational exercise on how to parse files in general (using CSV as an example), you may check out this article by Julian Bucknall. I like the article because it breaks things down into much smaller problems that are much less insurmountable. You first create a grammar, and once you have a good grammar, it's a relatively easy and methodical process to convert the grammar into code.

The article uses C# and has a link at the bottom to download the code.

Convert pandas dataframe to NumPy array

A simple way to convert dataframe to numpy array:

import pandas as pd
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
df_to_array = df.to_numpy()
array([[1, 3],
   [2, 4]])

Use of to_numpy is encouraged to preserve consistency.

Reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html

Upload file to SFTP using PowerShell

Using PuTTY's pscp.exe (which I have in an $env:path directory):

pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.

How to make a progress bar

I was writing up an answer to a similar question that got deleted, so I'm posting it here in case it's of use to anyone.

The markup can be dropped in anywhere and takes up 50px of vertical real estate even when hidden. (To have it take up no vertical space and instead overlay the top 50px, we can just give the progressContainerDiv absolute positioning (inside any positioned element) and style the display property instead of the visible property.)

The general structure is based on code presented in this Geeks for Geeks article.

_x000D_
_x000D_
const_x000D_
  progressContainerDiv = document.getElementById("progressContainerDiv");_x000D_
  progressShownDiv = document.getElementById("progressShownDiv");_x000D_
let_x000D_
  progress = 0,_x000D_
  percentageIncrease = 10;_x000D_
_x000D_
function animateProgress(){_x000D_
  progressContainerDiv.style.visibility = "visible";_x000D_
  const repeater = setInterval(increaseRepeatedly, 100);_x000D_
  function increaseRepeatedly(){_x000D_
    if(progress >= 100){_x000D_
      clearInterval(repeater);_x000D_
      progressContainerDiv.style.visibility = "hidden";_x000D_
      progressNumberSpan.innerHTML = "";_x000D_
      progress = 1;_x000D_
    }_x000D_
    else{_x000D_
      progress = Math.min(100, progress + percentageIncrease);_x000D_
      progressShownDiv.style.width = progress + "%";_x000D_
      progressNumberSpan.innerHTML = progress + "%";_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#progressContainerDiv{_x000D_
  visibility: hidden;_x000D_
  height: 40px;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
#progressBackgroundDiv {_x000D_
  width: 50%;_x000D_
  margin-left: 24%;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
  _x000D_
#progressShownDiv {_x000D_
  width: 1%;_x000D_
  height: 20px;_x000D_
  background-color: #4CAF50;_x000D_
}_x000D_
_x000D_
#progressNumberSpan{_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<div id="progressContainerDiv">_x000D_
  <div id="progressBackgroundDiv">_x000D_
    <div id="progressShownDiv"></div>_x000D_
  </div>_x000D_
  <div id="progressNumberContainerDiv">_x000D_
    <span id="progressNumberSpan"></span>_x000D_
  </div>_x000D_
</div>_x000D_
<button type="button" onclick="animateProgress()">Go</button>_x000D_
<div id="display"></div>
_x000D_
_x000D_
_x000D_

Editing legend (text) labels in ggplot

The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2 package.

An example with your data:

# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")

# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
  geom_point(size=5) +
  labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
        axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
        plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))

this results in:

enter image description here

As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888")) instead of scale_color_manual().

How do I fetch only one branch of a remote Git repository?

One way is the following:

git fetch <remotename> <remote branch>:refs/remotes/<remotename>/<local branch>

This does not set up tracking though.

For more information, see the documentation of git fetch.

EDIT: As @user1338062 notes below: if you don't already have a local clone of the repository where you want to add the new branch, but you want to create a fresh local repository, then the git clone --branch <branch_name> --single-branch <repo_url> provides a shorter solution.

Parsing jQuery AJAX response

Imagine that this is your Json response

{"Visit":{"VisitId":8,"Description":"visit8"}}

This is how you parse the response and access the values

    Ext.Ajax.request({
    headers: {
        'Content-Type': 'application/json'
    },
    url: 'api/fullvisit/getfullvisit/' + visitId,
    method: 'GET',
    dataType: 'json',
    success: function (response, request) {
        obj = JSON.parse(response.responseText);
        alert(obj.Visit.VisitId);
    }
});

This will alert the VisitId field

CryptographicException 'Keyset does not exist', but only through WCF

I just wanted to add a sanity check answer. I was getting the exact same error even after installing the certificates to the right stores on my machines and having all the right security privileges for the client. Turns out I mixed up my clientCertificate and my Service Certificate. If you have tried all of the above, I would double check that you have those two straight. Once I did that, my application successfully called the web service. Again, just a sanity checker.

How to close existing connections to a DB

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

curl.h no such file or directory

sudo apt-get install curl-devel

sudo apt-get install libcurl-dev

(will install the default alternative)

OR

sudo apt-get install libcurl4-openssl-dev

(the OpenSSL variant)

OR

sudo apt-get install libcurl4-gnutls-dev

(the gnutls variant)

Unzip files programmatically in .net

Use the DotNetZip library at http://www.codeplex.com/DotNetZip

class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files...

DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment...

If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952)...

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

Try this:

$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);

Inserting multiple rows in mysql

If you have your data in a text-file, you can use LOAD DATA INFILE.

When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.

Optimizing INSERT Statements

You can find more tips on how to speed up your insert statements on the link above.

Rails: Default sort order for a rails model?

default_scope

This works for Rails 4+:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

For Rails 2.3, 3, you need this instead:

default_scope order('created_at DESC')

For Rails 2.x:

default_scope :order => 'created_at DESC'

Where created_at is the field you want the default sorting to be done on.

Note: ASC is the code to use for Ascending and DESC is for descending (desc, NOT dsc !).

scope

Once you're used to that you can also use scope:

class Book < ActiveRecord::Base
  scope :confirmed, :conditions => { :confirmed => true }
  scope :published, :conditions => { :published => true }
end

For Rails 2 you need named_scope.

:published scope gives you Book.published instead of Book.find(:published => true).

Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed.

With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.

You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:

scope :recent_books, lambda 
  { |since_when| where("created_at >= ?", since_when) }
  # Note the `where` is making use of AREL syntax added in Rails 3.

Finally you can disable default scope with:

Book.with_exclusive_scope { find(:all) } 

or even better:

Book.unscoped.all

which will disable any filter (conditions) or sort (order by).

Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+


So ... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!

In fact they are Class level methods as they operate on the 1 set of 'all' records.

Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }.

As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published where published is a named scope.

In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

Session TimeOut in web.xml

Hacky way:

You could increase the session timeout programmatically when a large up-/download is expected.

session.setMaxInactiveInterval(TWO_HOURS_IN_SECONDS)

When the process ends, you could set the timeout back to its default.

But.. when you are on Java EE, and the up-/download doesn't take a complete hour, the better way was to run the tasks asynchronous (via JMS e.g.).

Understanding the difference between Object.create() and new SomeFunction()

Object creation variants.


Variant 1 : 'new Object()' -> Object constructor without arguments.

var p1 = new Object(); // 'new Object()' create and return empty object -> {}

var p2 = new Object(); // 'new Object()' create and return empty object -> {}

console.log(p1); // empty object -> {}

console.log(p2); // empty object -> {}

// p1 and p2 are pointers to different objects
console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

// empty object which is in fact Object.prototype
console.log(p1.__proto__); // {}

// empty object to which p1.__proto__ points
console.log(Object.prototype); // {}

console.log(p1.__proto__ === Object.prototype); // true

// null, which is in fact Object.prototype.__proto__
console.log(p1.__proto__.__proto__); // null

console.log(Object.prototype.__proto__); // null

enter image description here


Variant 2 : 'new Object(person)' -> Object constructor with argument.

const person = {
    name: 'no name',
    lastName: 'no lastName',
    age: -1
}

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p1 = new Object(person);

// 'new Object(person)' return 'person', which is pointer to the object ->
//  -> { name: 'no name', lastName: 'no lastName', age: -1 }
var p2 = new Object(person);

// person, p1 and p2 are pointers to the same object
console.log(p1 === p2); // true
console.log(p1 === person); // true
console.log(p2 === person); // true

p1.name = 'John'; // change 'name' by 'p1'
p2.lastName = 'Doe'; // change 'lastName' by 'p2'
person.age = 25; // change 'age' by 'person'

// when print 'p1', 'p2' and 'person', it's the same result,
// because the object they points is the same
console.log(p1); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(p2); // { name: 'John', lastName: 'Doe', age: 25 }
console.log(person); // { name: 'John', lastName: 'Doe', age: 25 }

enter image description here


Variant 3.1 : 'Object.create(person)'. Use Object.create with simple object 'person'. 'Object.create(person)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'person'.

const person = {
        name: 'no name',
        lastName: 'no lastName',
        age: -1,
        getInfo: function getName() {
           return `${this.name} ${this.lastName}, ${this.age}!`;
    }
}

var p1 = Object.create(person);

var p2 = Object.create(person);

// 'p1.__proto__' and 'p2.__proto__' points to
// the same object -> 'person'
// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(p1.__proto__);
console.log(p2.__proto__);
console.log(p1.__proto__ === p2.__proto__); // true

console.log(person.__proto__); // {}(which is the Object.prototype)

// 'person', 'p1' and 'p2' are different
console.log(p1 === person); // false
console.log(p1 === p2); // false
console.log(p2 === person); // false

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

console.log(p1); // empty object - {}

console.log(p2); // empty object - {}

// add properties to object 'p1'
// (properties with the same names like in object 'person')
p1.name = 'John';
p1.lastName = 'Doe';
p1.age = 25;

// add properties to object 'p2'
// (properties with the same names like in object 'person')
p2.name = 'Tom';
p2.lastName = 'Harrison';
p2.age = 38;

// { name: 'no name', lastName: 'no lastName', age: -1, getInfo: [Function: getName] }
console.log(person);

// { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// use by '__proto__'(link from 'p1' to 'person'),
// person's function 'getInfo'
console.log(p1.getInfo()); // John Doe, 25!

// use by '__proto__'(link from 'p2' to 'person'),
// person's function 'getInfo'
console.log(p2.getInfo()); // Tom Harrison, 38!

enter image description here


Variant 3.2 : 'Object.create(Object.prototype)'. Use Object.create with built-in object -> 'Object.prototype'. 'Object.create(Object.prototype)' will create(and return) new empty object and add property '__proto__' to the same new empty object. This property '__proto__' will point to the object 'Object.prototype'.

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p1' property '__proto__', which is link to 'Object.prototype'
var p1 = Object.create(Object.prototype);

// 'Object.create(Object.prototype)' :
// 1. create and return empty object -> {}.
// 2. add to 'p2' property '__proto__', which is link to 'Object.prototype'
var p2 = Object.create(Object.prototype);

console.log(p1); // {}

console.log(p2); // {}

console.log(p1 === p2); // false

console.log(p1.prototype); // undefined

console.log(p2.prototype); // undefined

console.log(p1.__proto__ === Object.prototype); // true

console.log(p2.__proto__ === Object.prototype); // true

enter image description here


Variant 4 : 'new SomeFunction()'

// 'this' in constructor-function 'Person'
// represents a new instace,
// that will be created by 'new Person(...)'
// and returned implicitly
function Person(name, lastName, age) {

    this.name = name;
    this.lastName = lastName;
    this.age = age;

    //-----------------------------------------------------------------
    // !--- only for demonstration ---
    // if add function 'getInfo' into
    // constructor-function 'Person',
    // then all instances will have a copy of the function 'getInfo'!
    //
    // this.getInfo: function getInfo() {
    //  return this.name + " " + this.lastName + ", " + this.age + "!";
    // }
    //-----------------------------------------------------------------
}

// 'Person.prototype' is an empty object
// (before add function 'getInfo')
console.log(Person.prototype); // Person {}

// With 'getInfo' added to 'Person.prototype',
// instances by their properties '__proto__',
// will have access to the function 'getInfo'.
// With this approach, instances not need
// a copy of the function 'getInfo' for every instance.
Person.prototype.getInfo = function getInfo() {
    return this.name + " " + this.lastName + ", " + this.age + "!";
}

// after function 'getInfo' is added to 'Person.prototype'
console.log(Person.prototype); // Person { getInfo: [Function: getInfo] }

// create instance 'p1'
var p1 = new Person('John', 'Doe', 25);

// create instance 'p2'
var p2 = new Person('Tom', 'Harrison', 38);

// Person { name: 'John', lastName: 'Doe', age: 25 }
console.log(p1);

// Person { name: 'Tom', lastName: 'Harrison', age: 38 }
console.log(p2);

// 'p1.__proto__' points to 'Person.prototype'
console.log(p1.__proto__); // Person { getInfo: [Function: getInfo] }

// 'p2.__proto__' points to 'Person.prototype'
console.log(p2.__proto__); // Person { getInfo: [Function: getInfo] }

console.log(p1.__proto__ === p2.__proto__); // true

// 'p1' and 'p2' points to different objects(instaces of 'Person')
console.log(p1 === p2); // false

// 'p1' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p1'-instance's data
console.log(p1.getInfo()); // John Doe, 25!

// 'p2' by its property '__proto__' reaches 'Person.prototype.getInfo' 
// and use 'getInfo' with 'p2'-instance's data
console.log(p2.getInfo()); // Tom Harrison, 38!

enter image description here

How to pass the -D System properties while testing on Eclipse?

run configuration -> arguments -> vm arguments

(can also be placed in the debug configuration under Debug Configuration->Arguments->VM Arguments)

How to initialise memory with new operator in C++?

Yes there is:

std::vector<int> vec(SIZE, 0);

Use a vector instead of a dynamically allocated array. Benefits include not having to bother with explicitely deleting the array (it is deleted when the vector goes out of scope) and also that the memory is automatically deleted even if there is an exception thrown.

Edit: To avoid further drive-by downvotes from people that do not bother to read the comments below, I should make it more clear that this answer does not say that vector is always the right answer. But it sure is a more C++ way than "manually" making sure to delete an array.

Now with C++11, there is also std::array that models a constant size array (vs vector that is able to grow). There is also std::unique_ptr that manages a dynamically allocated array (that can be combined with initialization as answered in other answers to this question). Any of those are a more C++ way than manually handling the pointer to the array, IMHO.

Purpose of Activator.CreateInstance with example?

Why would you use it if you already knew the class and were going to cast it? Why not just do it the old fashioned way and make the class like you always make it? There's no advantage to this over the way it's done normally. Is there a way to take the text and operate on it thusly:

label1.txt = "Pizza" 
Magic(label1.txt) p = new Magic(lablel1.txt)(arg1, arg2, arg3);
p.method1();
p.method2();

If I already know its a Pizza there's no advantage to:

p = (Pizza)somefancyjunk("Pizza"); over
Pizza p = new Pizza();

but I see a huge advantage to the Magic method if it exists.

How to verify element present or visible in selenium 2 (Selenium WebDriver)

To make sure that an element is present you can do the following:

driver.findElements(By.id("id"));

That will return an array, if that array size is > 0 then the element/s is present.

Also, you need to provide more information, such as language and what have you tried before asking,

Good luck

Javascript can't find element by id?

How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}

The other alternative is to keep your <script...</script> just before the closing </body> tag.

Show a div with Fancybox

As far as I know, an input element may not have a href attribute, which is where Fancybox gets its information about the content. The following code uses an a element instead of the input element. Also, this is what I would call the "standard way".

<html>
<head>
  <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
  <link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>

<a href="#divForm" id="btnForm">Load Form</a>

<div id="divForm" style="display:none">
  <form action="tbd">
    File: <input type="file" /><br /><br />
    <input type="submit" />
  </form>
</div>

<script type="text/javascript">
  $(function(){
    $("#btnForm").fancybox();
  });
</script>

</body>
</html>

See it in action on JSBin

How do I delete rows in a data frame?

Delete Dan from employee.data - No need to manage a new data.frame.

employee.data <- subset(employee.data, name!="Dan")

Android ListView not refreshing after notifyDataSetChanged

Try like this:

this.notifyDataSetChanged();

instead of:

adapter.notifyDataSetChanged();

You have to notifyDataSetChanged() to the ListView not to the adapter class.

How and when to use ‘async’ and ‘await’

The async is used with a function to makes it into an asynchronous function. The await keyword is used to invoke an asynchronous function synchronously. The await keyword holds the JS engine execution until promise is resolved.

We should use async & await only when we want the result immediately. Maybe the result is being returned from the function or getting used in the next line.

Follow this blog, It is very well written in simple word

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

md TEST_BACKUP_FOLDER
copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

Call asynchronous method in constructor?

You could put the async calls in a separate method and call that method in the constructor. Although, this may lead to a situation where some variable values not being available at the time you expect them.

 public NewTravelPageVM(){
   GetVenues();              
 }

 async void  GetVenues(){
   var locator = CrossGeolocator.Current;
   var position = await locator.GetPositionAsync();
   Venues = await Venue.GetVenues(position.Latitude, position.Longitude);
 }

How to disable a link using only CSS?

If you want it to be CSS only, the disabling logic should be defined by CSS.

To move the logic in the CSS definitions, you'll have to use attribute selectors. Here are some examples :

Disable link that has an exact href: =

You can choose to disable links that contain a specific href value like so :

<a href="//website.com/exact/path">Exact path</a>

[href="//website.com/exact/path"]{
  pointer-events: none;
}

Disable a link that contains a piece of path: *=

Here, any link containing /keyword/in path will be disabled

<a href="//website.com/keyword/in/path">Contains in path</a>

[href*="/keyword/"]{
  pointer-events: none;
}

Disable a link that begins with: ^=

the [attribute^=value] operator target an attribute that starts with a specific value. Allows you to discard websites & root paths.

<a href="//website.com/begins/with/path">Begins with path</a>

[href^="//website.com/begins/with"]{
  pointer-events: none;
}

You can even use it to disable non-https links. For example :

a:not([href^="https://"]){
  pointer-events: none;
}

Disable a link that ends with: $=

The [attribute$=value] operator target an attribute that ends with a specific value. It can be useful to discard file extensions.

<a href="/path/to/file.pdf">Link to pdf</a>

[href$=".pdf"]{
  pointer-events: none;
}

Or any other attribute

Css can target any HTML attribute. Could be rel, target, data-customand so on...

<a href="#" target="_blank">Blank link</a>

[target=_blank]{
  pointer-events: none;
}

Combining attribute selectors

You can chain multiple rules. Let's say that you want to disable every external link, but not those pointing to your website :

a[href*="//"]:not([href*="my-website.com"]) {
    pointer-events: none;
}

Or disable links to pdf files of a specific website :

<a href="//website.com/path/to/file.jpg">Link to image</a>

[href^="//website.com"][href$=".jpg"] {
  color: red;
}

Browser support

Attributes selectors are supported since IE7. :not() selector since IE9.

Flutter command not found

How to Install Flutter on MacOS To permanently add Flutter to your path, follow this command line

  1. Open (or create) the rc file for your shell. Typing echo $SHELL in your Terminal tells you which shell you’re using. If you’re using Bash, edit $HOME/.bash_profile or $HOME/.bashrc. If you’re using Z shell, edit $HOME/.zshrc. If you’re using a different shell, the file path and filename will be different on your machine.

    In your terminal, run:

    touch $HOME/.bash_profile
    
    vi $HOME/.bash_profile
    

In Catalina your default shell is ZSH, thus you can also replace the '(dot)bash_profile' to '(dot)zshrc' [without quote and replace the dot] and the rest is the same!

Also to check for environment is running, you can just type 'flutt' + TAB, and if autocomplete kicks in you are done!

  1. Add the following line and change [Flutter SDK] to be the path where you extracted Flutter SDK and save

    If this is not working:

    export PATH="$PATH: /Users/Desktop/flutter/bin"
    

    Try this instead:

    export PATH="$HOME/Users/Desktop/flutter/bin:$PATH"
    

Save the file and close it.

  1. Run source $HOME/.bash_profile to refresh the current window, or open a new terminal window to automatically source the file.

  2. And verify that the flutter/bin directory is now in your PATH by running:

    echo $PATH
    

For see more : https://www.youtube.com/watch?v=ZwUGHiroGBo

Convert Month Number to Month Name Function in SQL

This one worked for me:

@MetricMonthNumber (some number)

SELECT 
(DateName( month , DateAdd( month , @MetricMonthNumber - 1 , '1900-01-01' ) )) AS MetricMonthName
FROM TableName

From a post above from @leoinfo and @Valentino Vranken. Just did a quick select and it works.

What are advantages of Artificial Neural Networks over Support Vector Machines?

One thing to note is that the two are actually very related. Linear SVMs are equivalent to single-layer NN's (i.e., perceptrons), and multi-layer NNs can be expressed in terms of SVMs. See here for some details.

Why does the arrow (->) operator in C exist?

C also does a good job at not making anything ambiguous.

Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.

Trigger change event <select> using jquery

Give links in value of the option tag

<select size="1" name="links" onchange="window.location.href=this.value;">
   <option value="http://www.google.com">Google</option>
   <option value="http://www.yahoo.com">Yahoo</option>
</select>

Easy way to print Perl array? (with a little formatting)

Map can also be used, but sometimes hard to read when you have lots of things going on.

map{ print "element $_\n" }   @array; 

Import Libraries in Eclipse?

No, don't do it that way.

From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.

Tadaa!! :)

What is an optional value in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String? = "Bertie"

Optionals (along with Generics) are one of the most difficult Swift concepts to understand. Because of how they are written and used, it's easy to get a wrong idea of what they are. Compare the optional above to creating a normal String:

var name: String = "Bertie" // No "?" after String

From the syntax it looks like an optional String is very similar to an ordinary String. It's not. An optional String is not a String with some "optional" setting turned on. It's not a special variety of String. A String and an optional String are completely different types.

Here's the most important thing to know: An optional is a kind of container. An optional String is a container which might contain a String. An optional Int is a container which might contain an Int. Think of an optional as a kind of parcel. Before you open it (or "unwrap" in the language of optionals) you won't know if it contains something or nothing.

You can see how optionals are implemented in the Swift Standard Library by typing "Optional" into any Swift file and ?-clicking on it. Here's the important part of the definition:

enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

Optional is just an enum which can be one of two cases: .none or .some. If it's .some, there's an associated value which, in the example above, would be the String "Hello". An optional uses Generics to give a type to the associated value. The type of an optional String isn't String, it's Optional, or more precisely Optional<String>.

Everything Swift does with optionals is magic to make reading and writing code more fluent. Unfortunately this obscures the way it actually works. I'll go through some of the tricks later.

Note: I'll be talking about optional variables a lot, but it's fine to create optional constants too. I mark all variables with their type to make it easier to understand type types being created, but you don't have to in your own code.


How to create optionals

To create an optional, append a ? after the type you wish to wrap. Any type can be optional, even your own custom types. You can't have a space between the type and the ?.

var name: String? = "Bob" // Create an optional String that contains "Bob"
var peter: Person? = Person() // An optional "Person" (custom type)

// A class with a String and an optional String property
class Car {
var modelName: String // must exist
var internalName: String? // may or may not exist
}

Using optionals

You can compare an optional to nil to see if it has a value:

var name: String? = "Bob"
name = nil // Set name to nil, the absence of a value
if name != nil {
    print("There is a name")
}
if name == nil { // Could also use an "else"
    print("Name has no value")
}

This is a little confusing. It implies that an optional is either one thing or another. It's either nil or it's "Bob". This is not true, the optional doesn't transform into something else. Comparing it to nil is a trick to make easier-to-read code. If an optional equals nil, this just means that the enum is currently set to .none.


Only optionals can be nil

If you try to set a non-optional variable to nil, you'll get an error.

var red: String = "Red"
red = nil // error: nil cannot be assigned to type 'String'

Another way of looking at optionals is as a complement to normal Swift variables. They are a counterpart to a variable which is guaranteed to have a value. Swift is a careful language that hates ambiguity. Most variables are define as non-optionals, but sometimes this isn't possible. For example, imagine a view controller which loads an image either from a cache or from the network. It may or may not have that image at the time the view controller is created. There's no way to guarantee the value for the image variable. In this case you would have to make it optional. It starts as nil and when the image is retrieved, the optional gets a value.

Using an optional reveals the programmers intent. Compared to Objective-C, where any object could be nil, Swift needs you to be clear about when a value can be missing and when it's guaranteed to exist.


To use an optional, you "unwrap" it

An optional String cannot be used in place of an actual String. To use the wrapped value inside an optional, you have to unwrap it. The simplest way to unwrap an optional is to add a ! after the optional name. This is called "force unwrapping". It returns the value inside the optional (as the original type) but if the optional is nil, it causes a runtime crash. Before unwrapping you should be sure there's a value.

var name: String? = "Bob"
let unwrappedName: String = name!
print("Unwrapped name: \(unwrappedName)")

name = nil
let nilName: String = name! // Runtime crash. Unexpected nil.

Checking and using an optional

Because you should always check for nil before unwrapping and using an optional, this is a common pattern:

var mealPreference: String? = "Vegetarian"
if mealPreference != nil {
    let unwrappedMealPreference: String = mealPreference!
    print("Meal: \(unwrappedMealPreference)") // or do something useful
}

In this pattern you check that a value is present, then when you are sure it is, you force unwrap it into a temporary constant to use. Because this is such a common thing to do, Swift offers a shortcut using "if let". This is called "optional binding".

var mealPreference: String? = "Vegetarian"
if let unwrappedMealPreference: String = mealPreference {
    print("Meal: \(unwrappedMealPreference)") 
}

This creates a temporary constant (or variable if you replace let with var) whose scope is only within the if's braces. Because having to use a name like "unwrappedMealPreference" or "realMealPreference" is a burden, Swift allows you to reuse the original variable name, creating a temporary one within the bracket scope

var mealPreference: String? = "Vegetarian"
if let mealPreference: String = mealPreference {
    print("Meal: \(mealPreference)") // separate from the other mealPreference
}

Here's some code to demonstrate that a different variable is used:

var mealPreference: String? = "Vegetarian"
if var mealPreference: String = mealPreference {
    print("Meal: \(mealPreference)") // mealPreference is a String, not a String?
    mealPreference = "Beef" // No effect on original
}
// This is the original mealPreference
print("Meal: \(mealPreference)") // Prints "Meal: Optional("Vegetarian")"

Optional binding works by checking to see if the optional equals nil. If it doesn't, it unwraps the optional into the provided constant and executes the block. In Xcode 8.3 and later (Swift 3.1), trying to print an optional like this will cause a useless warning. Use the optional's debugDescription to silence it:

print("\(mealPreference.debugDescription)")

What are optionals for?

Optionals have two use cases:

  1. Things that can fail (I was expecting something but I got nothing)
  2. Things that are nothing now but might be something later (and vice-versa)

Some concrete examples:

  • A property which can be there or not there, like middleName or spouse in a Person class
  • A method which can return a value or nothing, like searching for a match in an array
  • A method which can return either a result or get an error and return nothing, like trying to read a file's contents (which normally returns the file's data) but the file doesn't exist
  • Delegate properties, which don't always have to be set and are generally set after initialization
  • For weak properties in classes. The thing they point to can be set to nil at any time
  • A large resource that might have to be released to reclaim memory
  • When you need a way to know when a value has been set (data not yet loaded > the data) instead of using a separate dataLoaded Boolean

Optionals don't exist in Objective-C but there is an equivalent concept, returning nil. Methods that can return an object can return nil instead. This is taken to mean "the absence of a valid object" and is often used to say that something went wrong. It only works with Objective-C objects, not with primitives or basic C-types (enums, structs). Objective-C often had specialized types to represent the absence of these values (NSNotFound which is really NSIntegerMax, kCLLocationCoordinate2DInvalid to represent an invalid coordinate, -1 or some negative value are also used). The coder has to know about these special values so they must be documented and learned for each case. If a method can't take nil as a parameter, this has to be documented. In Objective-C, nil was a pointer just as all objects were defined as pointers, but nil pointed to a specific (zero) address. In Swift, nil is a literal which means the absence of a certain type.


Comparing to nil

You used to be able to use any optional as a Boolean:

let leatherTrim: CarExtras? = nil
if leatherTrim {
    price = price + 1000
}

In more recent versions of Swift you have to use leatherTrim != nil. Why is this? The problem is that a Boolean can be wrapped in an optional. If you have Boolean like this:

var ambiguous: Boolean? = false

it has two kinds of "false", one where there is no value and one where it has a value but the value is false. Swift hates ambiguity so now you must always check an optional against nil.

You might wonder what the point of an optional Boolean is? As with other optionals the .none state could indicate that the value is as-yet unknown. There might be something on the other end of a network call which takes some time to poll. Optional Booleans are also called "Three-Value Booleans"


Swift tricks

Swift uses some tricks to allow optionals to work. Consider these three lines of ordinary looking optional code;

var religiousAffiliation: String? = "Rastafarian"
religiousAffiliation = nil
if religiousAffiliation != nil { ... }

None of these lines should compile.

  • The first line sets an optional String using a String literal, two different types. Even if this was a String the types are different
  • The second line sets an optional String to nil, two different types
  • The third line compares an optional string to nil, two different types

I'll go through some of the implementation details of optionals that allow these lines to work.


Creating an optional

Using ? to create an optional is syntactic sugar, enabled by the Swift compiler. If you want to do it the long way, you can create an optional like this:

var name: Optional<String> = Optional("Bob")

This calls Optional's first initializer, public init(_ some: Wrapped), which infers the optional's associated type from the type used within the parentheses.

The even longer way of creating and setting an optional:

var serialNumber:String? = Optional.none
serialNumber = Optional.some("1234")
print("\(serialNumber.debugDescription)")

Setting an optional to nil

You can create an optional with no initial value, or create one with the initial value of nil (both have the same outcome).

var name: String?
var name: String? = nil

Allowing optionals to equal nil is enabled by the protocol ExpressibleByNilLiteral (previously named NilLiteralConvertible). The optional is created with Optional's second initializer, public init(nilLiteral: ()). The docs say that you shouldn't use ExpressibleByNilLiteral for anything except optionals, since that would change the meaning of nil in your code, but it's possible to do it:

class Clint: ExpressibleByNilLiteral {
    var name: String?
    required init(nilLiteral: ()) {
        name = "The Man with No Name"
    }
}

let clint: Clint = nil // Would normally give an error
print("\(clint.name)")

The same protocol allows you to set an already-created optional to nil. Although it's not recommended, you can use the nil literal initializer directly:

var name: Optional<String> = Optional(nilLiteral: ())

Comparing an optional to nil

Optionals define two special "==" and "!=" operators, which you can see in the Optional definition. The first == allows you to check if any optional is equal to nil. Two different optionals which are set to .none will always be equal if the associated types are the same. When you compare to nil, behind the scenes Swift creates an optional of the same associated type, set to .none then uses that for the comparison.

// How Swift actually compares to nil
var tuxedoRequired: String? = nil
let temp: Optional<String> = Optional.none
if tuxedoRequired == temp { // equivalent to if tuxedoRequired == nil
    print("tuxedoRequired is nil")
}

The second == operator allows you to compare two optionals. Both have to be the same type and that type needs to conform to Equatable (the protocol which allows comparing things with the regular "==" operator). Swift (presumably) unwraps the two values and compares them directly. It also handles the case where one or both of the optionals are .none. Note the distinction between comparing to the nil literal.

Furthermore, it allows you to compare any Equatable type to an optional wrapping that type:

let numberToFind: Int = 23
let numberFromString: Int? = Int("23") // Optional(23)
if numberToFind == numberFromString {
    print("It's a match!") // Prints "It's a match!"
}

Behind the scenes, Swift wraps the non-optional as an optional before the comparison. It works with literals too (if 23 == numberFromString {)

I said there are two == operators, but there's actually a third which allow you to put nil on the left-hand side of the comparison

if nil == name { ... }

Naming Optionals

There is no Swift convention for naming optional types differently from non-optional types. People avoid adding something to the name to show that it's an optional (like "optionalMiddleName", or "possibleNumberAsString") and let the declaration show that it's an optional type. This gets difficult when you want to name something to hold the value from an optional. The name "middleName" implies that it's a String type, so when you extract the String value from it, you can often end up with names like "actualMiddleName" or "unwrappedMiddleName" or "realMiddleName". Use optional binding and reuse the variable name to get around this.


The official definition

From "The Basics" in the Swift Programming Language:

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.


To finish, here's a poem from 1899 about optionals:

Yesterday upon the stair
I met a man who wasn’t there
He wasn’t there again today
I wish, I wish he’d go away

Antigonish


More resources: