Programs & Examples On #Migrate

Migration is the process of moving data from container to another. This includes migration to and from physical containers (e.g. hard disks) and migration to and from logical containers.

Moving Git repository content to another repository preserving history

This worked to move my local repo (including history) to my remote github.com repo. After creating the new empty repo at GitHub.com I use the URL in step three below and it works great.

git clone --mirror <url_of_old_repo>
cd <name_of_old_repo>
git remote add new-origin <url_of_new_repo>
git push new-origin --mirror

I found this at: https://gist.github.com/niksumeiko/8972566

Copy tables from one database to another in SQL Server

SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.

If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.

I use this all the time and it works fairly well.

How do you migrate an IIS 7 site to another server?

use appcmd to export one or all the sites out then reimport into the new server. It could be iis7.0 or 7.5 When you export out using appcmd, the passwords are decrypted, then reimport and they will reencrypt.

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

POST data in JSON format

Not sure if you want jQuery.

var form;

form.onsubmit = function (e) {
  // stop the regular form submission
  e.preventDefault();

  // collect the form data while iterating over the inputs
  var data = {};
  for (var i = 0, ii = form.length; i < ii; ++i) {
    var input = form[i];
    if (input.name) {
      data[input.name] = input.value;
    }
  }

  // construct an HTTP request
  var xhr = new XMLHttpRequest();
  xhr.open(form.method, form.action, true);
  xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

  // send the collected data as JSON
  xhr.send(JSON.stringify(data));

  xhr.onloadend = function () {
    // done
  };
};

Using BufferedReader.readLine() in a while loop properly

In addition to the answer given by @ramin, if you already have BufferedReader or InputStream, it's possible to iterate through lines like this:

reader.lines().forEach(line -> {
    //...
});

or if you need to process it with given order:

reader.lines().forEachOrdered(line -> {
    //...
});

How can I find all *.js file in directory recursively in Linux?

find /abs/path/ -name '*.js'

Edit: As Brian points out, add -type f if you want only plain files, and not directories, links, etc.

Can HTML be embedded inside PHP "if" statement?

Yes,

<?php
if ( $my_name == "someguy" ) {
    ?> HTML GOES HERE <?php;
}
?>

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

How to configure welcome file list in web.xml

This is my way to setup Servlet as welcome page.

I share for whom concern.

web.xml

  <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Demo</servlet-name>
        <servlet-class>servlet.Demo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Demo</servlet-name>
        <url-pattern></url-pattern>
    </servlet-mapping>

Servlet class

@WebServlet(name = "/demo")
public class Demo extends HttpServlet {
   public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException  {
       RequestDispatcher rd = req.getRequestDispatcher("index.jsp");
   }
}

Makefile: How to correctly include header file and its directory?

The preprocessor is looking for StdCUtil/split.h in

and in

  • $INC_DIR (i.e. ../StdCUtil/ = /root/Core/../StdCUtil/ = /root/StdCUtil/). So ../StdCUtil/ + StdCUtil/split.h = ../StdCUtil/StdCUtil/split.h and the file is missing

You can fix the error changing the $INC_DIR variable (best solution):

$INC_DIR = ../

or the include directive:

#include "split.h"

but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.

Reference:

EDIT/UPDATE

It should also be

CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)

...

%.o: %.cpp $(DEPS)
    $(CXX) -o $@ $< $(CXXFLAGS)

Retrieve only the queried element in an object array in MongoDB collection

Along with $project it will be more appropriate other wise matching elements will be clubbed together with other elements in document.

db.test.aggregate(
  { "$unwind" : "$shapes" },
  { "$match" : { "shapes.color": "red" } },
  { 
    "$project": {
      "_id":1,
      "item":1
    }
  }
)

nodejs get file name from absolute path?

In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform. Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.

How to auto generate migrations with Sequelize CLI from Sequelize models?

You can now use the npm package sequelize-auto-migrations to automatically generate a migrations file. https://www.npmjs.com/package/sequelize-auto-migrations

Using sequelize-cli, initialize your project with

sequelize init

Create your models and put them in your models folder.

Install sequelize-auto-migrations:

npm install sequelize-auto-migrations

Create an initial migration file with

node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>

Run your migration:

node ./node_modules/sequelize-auto-migrations/bin/runmigration

You can also automatically generate your models from an existing database, but that is beyond the scope of the question.

CSS float right not working correctly

LIke this

final answer

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

demo1

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: gray;
    float: left;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

html

<h2>
Contact Details</h2>
<button type="button" class="edit_button" >My Button</button>

demo

html

<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray; float:left;">
Contact Details



</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>

Using Bootstrap Tooltip with AngularJS

Only read this if you are assigning tooltips dynamically

i.e. <div tooltip={{ obj.somePropertyThatMayChange }} ...></div>

I had an issue with dynamic tooltips that were not always updating with the view. For example, I was doing something like this:

This didn't work consistently

<div ng-repeat="person in people">
    <span data-toggle="tooltip" data-placement="top" title="{{ person.tooltip }}">
      {{ person.name }}
    </span> 
</div> 

And activating it as so:

$timeout(function() {
  $(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 1500)

However, as my people array would change my tooltips wouldn't always update. I tried every fix in this thread and others with no luck. The glitch seemed to only be happening around 5% of the time, and was nearly impossible to repeat.

Unfortunately, these tooltips are mission critical for my project, and showing an incorrect tooltip could be very bad.

What seemed to be the issue

Bootstrap was copying the value of the title property to a new attribute, data-original-title and removing the title property (sometimes) when I would activate the toooltips. However, when my title={{ person.tooltip }} would change the new value would not always be updated into the property data-original-title. I tried deactivating the tooltips and reactivating them, destroying them, binding to this property directly... everything. However each of these either didn't work or created new issues; such as the title and data-original-title attributes both being removed and un-bound from my object.

What did work

Perhaps the most ugly code I've ever pushed, but it solved this small but substantial problem for me. I run this code each time the tooltip is update with new data:

$timeout(function() {
    $('[data-toggle="tooltip"]').each(function(index) {
      // sometimes the title is blank for no apparent reason. don't override in these cases.
      if ($(this).attr("title").length > 0) {
        $( this ).attr("data-original-title", $(this).attr("title"));
      }
    });
    $timeout(function() {
      // finally, activate the tooltips
      $(document).tooltip({ selector: '[data-toggle="tooltip"]'});
    }, 500);
}, 1500);

What's happening here in essence is:

  • Wait some time (1500 ms) for the digest cycle to complete, and the titles to be updated.
  • If there's a title property that is not empty (i.e. it has changed), copy it to the data-original-title property so it will be picked up by Bootstrap's toolips.
  • Reactivate the tooltips

Hope this long answer helps someone who may have been struggling as I was.

Given a filesystem path, is there a shorter way to extract the filename without its extension?

You can use Path API as follow:

 var filenNme = Path.GetFileNameWithoutExtension([File Path]);

More info: Path.GetFileNameWithoutExtension

Ruby: character to ascii from a string

Ruby String provides the codepoints method after 1.9.1.

str = 'hello world'
str.codepoints.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 

str = "????"
str.codepoints.to_a
=> [20320, 22909, 19990, 30028]

Stop fixed position at footer

I've made some changes to the second most popular answer as i found this worked better for me. The changes use window.innerHeight as it is more dynamic than adding your own height for the nav (above used + 570). this allows the code to work on mobile, tablet and desktop dynamicly.

$(window).scroll(() => {
            //Distance from top fo document to top of footer
            topOfFooter = $('#footer').position().top;
             // Distance user has scrolled from top + windows inner height
             scrollDistanceFromTopOfDoc = $(document).scrollTop() + window.innerHeight;
             // Difference between the two.
             scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter; 
            // If user has scrolled further than footer,
              if (scrollDistanceFromTopOfDoc > topOfFooter) {
                // add margin-bottom so button stays above footer.
                $('#floating-button').css('margin-bottom',  0 + scrollDistanceFromTopOfFooter);
              } else  {
                // remove margin-bottom so button goes back to the bottom of the page
                $('#floating-button').css('margin-bottom', 0);
              }
            });

How to print all session variables currently set?

session_start();
echo '<pre>';var_dump($_SESSION);echo '</pre>';
// or
echo '<pre>';print_r($_SESSION);echo '</pre>';

NOTE: session_start(); line is must then only you will able to print the value $_SESSION

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

SQL statement to select all rows from previous day

In SQL Server do like this:

where cast(columnName as date) = cast(getdate() -1 as date)

You should cast both sides of the expression to date to avoid issues with time formatting.

If you need to control interval in more detail, then you should try something like:

declare @start datetime = cast(getdate() - 1 as date)
declare @end datetime = cast(getdate() - 1 as date)
set @end = dateadd(second, 86399, @end)

How to plot all the columns of a data frame in R

The ggplot2 package takes a little bit of learning, but the results look really nice, you get nice legends, plus many other nice features, all without having to write much code.

require(ggplot2)
require(reshape2)
df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))
df <- melt(df ,  id.vars = 'time', variable.name = 'series')

# plot on same grid, each series colored differently -- 
# good if the series have same scale
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))

# or plot on different plots
ggplot(df, aes(time,value)) + geom_line() + facet_grid(series ~ .)

enter image description here enter image description here

@try - catch block in Objective-C

Objective-C is not Java. In Objective-C exceptions are what they are called. Exceptions! Don’t use them for error handling. It’s not their proposal. Just check the length of the string before using characterAtIndex and everything is fine....

how to use a like with a join in sql?

In MySQL you could try:

SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');

Of course this would be a massively inefficient query because it would do a full table scan.

Update: Here's a proof


create table A (MYCOL varchar(255));
create table B (MYCOL varchar(255));
insert into A (MYCOL) values ('foo'), ('bar'), ('baz');
insert into B (MYCOL) values ('fooblah'), ('somethingfooblah'), ('foo');
insert into B (MYCOL) values ('barblah'), ('somethingbarblah'), ('bar');
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
+-------+------------------+
| MYCOL | MYCOL            |
+-------+------------------+
| foo   | fooblah          |
| foo   | somethingfooblah |
| foo   | foo              |
| bar   | barblah          |
| bar   | somethingbarblah |
| bar   | bar              |
+-------+------------------+
6 rows in set (0.38 sec)

AngularJS - Trigger when radio button is selected

In newer versions of angular (I'm using 1.3) you can basically set the model and the value and the double binding do all the work this example works like a charm:

_x000D_
_x000D_
angular.module('radioExample', []).controller('ExampleController', ['$scope', function($scope) {_x000D_
  $scope.color = {_x000D_
    name: 'blue'_x000D_
  };_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
<html>_x000D_
<body ng-app="radioExample">_x000D_
<form name="myForm" ng-controller="ExampleController">_x000D_
  <input type="radio" ng-model="color.name" value="red">  Red <br/>_x000D_
  <input type="radio" ng-model="color.name" value="green"> Green <br/>_x000D_
  <input type="radio" ng-model="color.name" value="blue"> Blue <br/>_x000D_
  <tt>color = {{color.name}}</tt><br/>_x000D_
 </form>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Java abstract interface

It's not necessary, it's optional, just as public on interface methods.

See the JLS on this:

http://java.sun.com/docs/books/jls/second_edition/html/interfaces.doc.html

9.1.1.1 abstract Interfaces Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.

And

9.4 Abstract Method Declarations

[...]

For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces.

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

How do I get the total number of unique pairs of a set in the database?

What you're looking for is n choose k. Basically:

enter image description here

For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

It's the Simple way to convert to format

 DateTime.Now.ToString("yyyyMMdd");

How to restart kubernetes nodes?

In my case I am running 3 nodes in VM's by using Hyper-V. By using the following steps I was able to "restart" the cluster after restarting all VM's.

  1. (Optional) Swap off

    $ swapoff -a

  2. You have to restart all Docker containers

    $ docker restart $(docker ps -a -q)

  3. Check the nodes status after you performed step 1 and 2 on all nodes (the status is NotReady)

    $ kubectl get nodes

  4. Restart the node

    $ systemctl restart kubelet

  5. Check again the status (now should be in Ready status)

Note: I do not know if it does metter the order of nodes restarting, but I choose to start with the k8s master node and after with the minions. Also it will take a little bit to change the node state from NotReady to Ready

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

If you would like to ignore case you could use the following:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

How to get back to most recent version in Git?

With Git 2.23+ (August 2019), the best practice would be to use git switch instead of the confusing git checkout command.

To create a new branch based on an older version:

git switch -c temp_branch HEAD~2

To go back to the current master branch:

git switch master

How to wait for a JavaScript Promise to resolve before resuming function?

You can do it manually. (I know, that that isn't great solution, but..) use while loop till the result hasn't a value

kickOff().then(function(result) {
   while(true){
       if (result === undefined) continue;
       else {
            $("#output").append(result);
            return;
       }
   }
});

How to convert string to binary?

This is an update for the existing answers which used bytearray() and can not work that way anymore:

>>> st = "hello world"
>>> map(bin, bytearray(st))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding

Because, as explained in the link above, if the source is a string, you must also give the encoding:

>>> map(bin, bytearray(st, encoding='utf-8'))
<map object at 0x7f14dfb1ff28>

Comparing double values in C#

Double (called float in some languages) is fraut with problems due to rounding issues, it's good only if you need approximate values.

The Decimal data type does what you want.

For reference decimal and Decimal are the same in .NET C#, as are the double and Double types, they both refer to the same type (decimal and double are very different though, as you've seen).

Beware that the Decimal data type has some costs associated with it, so use it with caution if you're looking at loops etc.

How do I tell matplotlib that I am done with a plot?

If none of them are working then check this.. say if you have x and y arrays of data along respective axis. Then check in which cell(jupyter) you have initialized x and y to empty. This is because , maybe you are appending data to x and y without re-initializing them. So plot has old data too. So check that..

GitLab remote: HTTP Basic: Access denied and fatal Authentication

When I had the same problem,

I solved it by removing the file "passwd" in

C:\Users\<USERNAME>\AppData\Local\Atlassian\SourceTree

After removing Sourcetree will prompt for the password.

Note:
OS Version : win10 
Sourcetree Version:  3.1

SELECT with a Replace()

Don't use the alias (P) in your WHERE clause directly.

You can either use the same REPLACE logic again in the WHERE clause:

SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'

Or use an aliased sub query as described in Nick's answers.

How can you encode a string to Base64 in JavaScript?

From here:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

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

    input = Base64._utf8_encode(input);

    while (i < input.length) {

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

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

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

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

    }

    return output;
},

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

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

    while (i < input.length) {

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

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

        output = output + String.fromCharCode(chr1);

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

    }

    output = Base64._utf8_decode(output);

    return output;

},

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

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

        var c = string.charCodeAt(n);

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

    }

    return utftext;
},

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

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

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

    }

    return string;
}

}

Also, search on "javascript base64 encoding" turns a lot of other options, the above was the first one.

Uploading Files in ASP.net without using the FileUpload server control

Here is a solution without relying on any server-side control, just like OP has described in the question.

Client side HTML code:

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

Page_Load method of upload.aspx :

if(Request.Files["UploadedFile"] != null)
{
    HttpPostedFile MyFile = Request.Files["UploadedFile"];
    //Setting location to upload files
    string TargetLocation = Server.MapPath("~/Files/");
    try
    {
        if (MyFile.ContentLength > 0)
        {
            //Determining file name. You can format it as you wish.
            string FileName = MyFile.FileName;
            //Determining file size.
            int FileSize = MyFile.ContentLength;
            //Creating a byte array corresponding to file size.
            byte[] FileByteArray = new byte[FileSize];
            //Posted file is being pushed into byte array.
            MyFile.InputStream.Read(FileByteArray, 0, FileSize);
            //Uploading properly formatted file to server.
            MyFile.SaveAs(TargetLocation + FileName);
        }
    }
    catch(Exception BlueScreen)
    {
        //Handle errors
    }
}

How to transfer paid android apps from one google account to another google account

Google has this to say on transferring data between accounts.

http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304

It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.

It's conveniently titled: "Moving Product Data"

http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582

What is the best way to search the Long datatype within an Oracle database?

Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.

Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.

Android Studio and Gradle build error

I used a local distribution of gradle downloaded from gradle website and used it in android studio.

It fixed the gradle build error.

How do I disable and re-enable a button in with javascript?

you can try with

document.getElementById('btn').disabled = !this.checked"

_x000D_
_x000D_
<input type="submit" name="btn"  id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox"  onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
_x000D_
_x000D_

What is the yield keyword used for in C#?

Recently Raymond Chen also ran an interesting series of articles on the yield keyword.

While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine. No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).

Is there functionality to generate a random character in Java?

private static char rndChar () {
    int rnd = (int) (Math.random() * 52); // or use Random or whatever
    char base = (rnd < 26) ? 'A' : 'a';
    return (char) (base + rnd % 26);

}

Generates values in the ranges a-z, A-Z.

Multiple Inheritance in C#

You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.

Test or check if sheet exists

In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:

=ISREF(INDIRECT("SheetName!A1"))

This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.

Best way in asp.net to force https for an entire site?

It also depends on the brand of your balancer, for the web mux, you would need to look for http header X-WebMux-SSL-termination: true to figure that incoming traffic was ssl. details here: http://www.cainetworks.com/support/redirect2ssl.html

What does -> mean in C++?

  1. Access operator applicable to (a) all pointer types, (b) all types which explicitely overload this operator
  2. Introducer for the return type of a local lambda expression:

    std::vector<MyType> seq;
    // fill with instances...  
    std::sort(seq.begin(), seq.end(),
                [] (const MyType& a, const MyType& b) -> bool {
                    return a.Content < b.Content;
                });
    
  3. introducing a trailing return type of a function in combination of the re-invented auto:

    struct MyType {
        // declares a member function returning std::string
        auto foo(int) -> std::string;
    };
    

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

How to confirm RedHat Enterprise Linux version?

I assume that you've run yum upgrade. That will in general update you to the newest minor release.

Your main resources for determining the version are /etc/redhat_release and lsb_release -a

How can I check if a View exists in a Database?

if exists (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') )

Android : Capturing HTTP Requests with non-rooted android device

You could install Charles - an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet - on your PC or MAC.

Config steps:

  • Let your phone and PC or MAC in a same LAN
  • Launch Charles which you installed (default proxy port is 8888)
  • Setup your phone's wifi configuration: set the ip of delegate to your PC or MAC's ip, port of delegate to 8888
  • Lauch your app in your phone. And monitor http requests on Charles.

Window vs Page vs UserControl for WPF navigation?

Most of all has posted correct answer. I would like to add few links, so that you can refer to them and have clear and better ideas about the same:

UserControl: http://msdn.microsoft.com/en-IN/library/a6h7e207(v=vs.71).aspx

The difference between page and window with respect to WPF: Page vs Window in WPF?

How to generate a random string of 20 characters

I'd use this approach:

String randomString(final int length) {
    Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString();
}

If you want a byte[] you can do this:

byte[] randomByteString(final int length) {
    Random r = new Random();
    byte[] result = new byte[length];
    for(int i = 0; i < length; i++) {
        result[i] = r.nextByte();
    }
    return result;
}

Or you could do this

byte[] randomByteString(final int length) {
    Random r = new Random();
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString().getBytes();
}

Bootstrap close responsive menu "on click"

Bootstrap 4 solution without any Javascript

Add attributes data-toggle="collapse" data-target="#navbarSupportedContent.show" to the div <div class="collapse navbar-collapse">

Make sure you provide the correct id in data-target

<div className="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">

.show is to avoid menu flickering in large resolutions

_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
  <div class="collapse navbar-collapse" id="navbarSupportedContent" data-toggle="collapse" data-target="#navbarSupportedContent.show">_x000D_
    <ul class="navbar-nav mr-auto">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Link</a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown_x000D_
        </a>_x000D_
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <div class="dropdown-divider"></div>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link disabled" href="#">Disabled</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
    <form class="form-inline my-2 my-lg-0">_x000D_
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">_x000D_
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>_x000D_
    </form>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Is there any boolean type in Oracle databases?

Just because nobody mentioned it yet: using RAW(1) also seems common practice.

Sync data between Android App and webserver

one way to accomplish this to have a server side application that waits for the data. The data can be sent using HttpRequest objects in Java or you can write your own TCP/IP data transfer utility. Data can be sent using JSON format or any other format that you think is suitable. Also data can be encrypted before sending to server if it contains sensitive information. All Server application have to do is just wait for HttpRequests to come in and parse the data and store it anywhere you want.

Create Excel files from C# without office

An interop calls something else, it's an interoperability assembly, so you're inter-operating with something...in this case Excel, the actual installed Excel.

In this case yes, it will fail to run because it depends on excel, you're just calling excel functions. If they don't have it installed...out of luck.

There are methods to generate without Excel, provided the 2007 file format is ok, here's a few:

as I said though, this is the 2007 format, normally if anything, that's the deal-breaker.

jQuery - Fancybox: But I don't want scrollbars!

I had a similar problem, with vertical scrollbars appearing when I set a maxWidth in the Fancybox options.

To get around the problem I had to set

.fancybox-inner {
   overflow: hidden !important;
}

and set a fixed width CSS rule on the Fancybox content rather than specifying a maxWidth in the Fancybox options. If I did the latter, Fancybox's calculated height for the content was slightly too small - probably hinting at why it was putting in scrollbars in the first place.

How to use Ajax.ActionLink?

@Ajax.ActionLink requires jQuery AJAX Unobtrusive library. You can download it via nuget:

Install-Package Microsoft.jQuery.Unobtrusive.Ajax

Then add this code to your View:

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")

How to get a vCard (.vcf file) into Android contacts from website

AFAIK Android doesn't support vCard files out of the Box at least not until 2.2.

You could use the app vCardIO to read vcf files from your SD card and save to you contacts. So you have to save them on your SD card in the first place and import them afterwards.

vCardIO is also available trough the market.

CSS Animation and Display None

I had the same problem, because as soon as display: x; is in animation, it won't animate.

I ended up in creating custom keyframes, first changing the display value then the other values. May give a better solution.

Or, instead of using display: none; use position: absolute; visibility: hidden; It should work.

CLEAR SCREEN - Oracle SQL Developer shortcut?

If you're using sqlplus in a shell, like bash you can run the shell's clear command from sqlplus:

SQL> host clear

you can abbreviate of course:

SQL> ho clear

Remove Primary Key in MySQL

ALTER TABLE `user_customer_permission` MODIFY `id` INT;
ALTER TABLE `user_customer_permission` DROP PRIMARY KEY;

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

The problem is that dataTable is not defined at the point you are calling this method.

Ensure that you are loading the .js files in the correct order:

<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>

ReactJS call parent method

Pass the method from Parent component down as a prop to your Child component. ie:

export default class Parent extends Component {
  state = {
    word: ''
  }

  handleCall = () => {
    this.setState({ word: 'bar' })
  }

  render() {
    const { word } = this.state
    return <Child handler={this.handleCall} word={word} />
  }
}

const Child = ({ handler, word }) => (
<span onClick={handler}>Foo{word}</span>
)

Partly cherry-picking a commit with Git

Actually, the best solution for this question is to use checkout commend

git checkout <branch> <path1>,<path2> ..

For example, assume you are in master, you want to the changes from dev1 on project1/Controller/WebController1.java and project1/Service/WebService1.java, you can use this:

git checkout dev1 project1/Controller/WebController1.java project1/Service/WebService1.java

That means the master branch only updates from dev1 on those two paths.

NoClassDefFoundError - Eclipse and Android

sometimes you have to take the whole external project as library and not only the jar:

my problem solved by adding the whole project (in my case google-play-services_lib) as library and not only the jar. the steps to to it (from @style answer):

  1. File->New->Other
  2. Select Android Project
  3. Select "Create Project from existing source"
  4. Click "Browse..." button and navigate to the wanted project
  5. Finish (Now action bar project in your workspace)
  6. Right-click on your project -> Properties
  7. In Android->Library section click Add
  8. select recently added project -> Ok

Remove non-utf8 characters from string

Welcome to 2019 and the /u modifier in regex which will handle UTF-8 multibyte chars for you

If you only use mb_convert_encoding($value, 'UTF-8', 'UTF-8') you will still end up with non-printable chars in your string

This method will:

  • Remove all invalid UTF-8 multibyte chars with mb_convert_encoding
  • Remove all non-printable chars like \r, \x00 (NULL-byte) and other control chars with preg_replace

method:

function utf8_filter(string $value): string{
    return preg_replace('/[^[:print:]\n]/u', '', mb_convert_encoding($value, 'UTF-8', 'UTF-8'));
}

[:print:] match all printable chars and \n newlines and strip everything else

You can see the ASCII table below.. The printable chars range from 32 to 127, but newline \n is a part of the control chars which range from 0 to 31 so we have to add newline to the regex /[^[:print:]\n]/u

https://cdn.shopify.com/s/files/1/1014/5789/files/Standard-ASCII-Table_large.jpg?10669400161723642407

You can try to send strings through the regex with chars outside the printable range like \x7F (DEL), \x1B (Esc) etc. and see how they are stripped

function utf8_filter(string $value): string{
    return preg_replace('/[^[:print:]\n]/u', '', mb_convert_encoding($value, 'UTF-8', 'UTF-8'));
}

$arr = [
    'Danish chars'          => 'Hello from Denmark with æøå',
    'Non-printable chars'   => "\x7FHello with invalid chars\r \x00"
];

foreach($arr as $k => $v){
    echo "$k:\n---------\n";
    
    $len = strlen($v);
    echo "$v\n(".$len.")\n";
    
    $strip = utf8_decode(utf8_filter(utf8_encode($v)));
    $strip_len = strlen($strip);
    echo $strip."\n(".$strip_len.")\n\n";
    
    echo "Chars removed: ".($len - $strip_len)."\n\n\n";
}

https://www.tehplayground.com/q5sJ3FOddhv1atpR

Using SimpleXML to create an XML object from scratch

Please see my answer here. As dreamwerx.myopenid.com points out, it is possible to do this with SimpleXML, but the DOM extension would be the better and more flexible way. Additionally there is a third way: using XMLWriter. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.

$w=new XMLWriter();
$w->openMemory();
$w->startDocument('1.0','UTF-8');
$w->startElement("root");
    $w->writeAttribute("ah", "OK");
    $w->text('Wow, it works!');
$w->endElement();
echo htmlentities($w->outputMemory(true));

By the way: DOM stands for Document Object Model; this is the standardized API into XML documents.

Using :focus to style outer div?

Simple use JQuery.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("div .FormRow").focusin(function() {_x000D_
    $(this).css("background-color", "#FFFFCC");_x000D_
    $(this).css("border", "3px solid #555");_x000D_
  });_x000D_
  $("div .FormRow").focusout(function() {_x000D_
    $(this).css("background-color", "#FFFFFF");_x000D_
    $(this).css("border", "0px solid #555");_x000D_
  });_x000D_
});
_x000D_
    .FormRow {_x000D_
      padding: 10px;_x000D_
    }
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div style="border: 0px solid black;padding:10px;">_x000D_
    <div class="FormRow">_x000D_
      First Name:_x000D_
      <input type="text">_x000D_
      <br>_x000D_
    </div>_x000D_
    <div class="FormRow">_x000D_
      Last Name:_x000D_
      <input type="text">_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <ul>_x000D_
    <li><strong><em>Click an input field to get focus.</em></strong>_x000D_
    </li>_x000D_
    <li><strong><em>Click outside an input field to lose focus.</em></strong>_x000D_
    </li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Why use Redux over Facebook Flux?

According to this article: https://medium.freecodecamp.org/a-realworld-comparison-of-front-end-frameworks-with-benchmarks-2019-update-4be0d3c78075

You better use MobX to manage the data in your app to get better performance, not Redux.

Asp.net MVC ModelState.Clear

I had an instance where I wanted to update the model of a sumitted form, and did not want to 'Redirect To Action' for performanace reason. Previous values of hidden fields were being retained on my updated model - causing allsorts of issues!.

A few lines of code soon identified the elements within ModelState that I wanted to remove (after validation), so the new values were used in the form:-

while (ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")).Value != null)
{
    ModelState.Remove(ModelState.FirstOrDefault(ms => ms.Key.ToString().StartsWith("SearchResult")));
}

Android ImageView Fixing Image Size

Try this

ImageView img
    Bitmap bmp;
    int width=100;
    int height=100;
    img=(ImageView)findViewById(R.id.imgView);
    bmp=BitmapFactory.decodeResource(getResources(),R.drawable.image);//image is your image                                                            
    bmp=Bitmap.createScaledBitmap(bmp, width,height, true);
    img.setImageBitmap(bmp);

Or If you want to load complete image size in memory then you can use

<ImageView
    android:id="@+id/img"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/image" 
    android:scaleType="fitXY"/>

Should I Dispose() DataSet and DataTable?

Datasets implement IDisposable thorough MarshalByValueComponent, which implements IDisposable. Since datasets are managed there is no real benefit to calling dispose.

Is Tomcat running?

Are you trying to set up an alert system? For a simple "heartbeat", do a HTTP request to the Tomcat port.

For more elaborate monitoring, you can set up JMX and/or SNMP to view JVM stats. We run Nagios with the SNMP plugin (bridges to JMX) to check Tomcat memory usage and request thread pool size every 10-15 minutes.

http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html

Update (2012):

We have upgraded our systems to use "monit" to check the tomcat process. I really like it. With very little configuration it automatically verifies the service is running, and automatically restarts if it is not. (sending an email alert). It can integrate with the /etc/init.d scripts or check by process name.

Circular gradient in android

<gradient
    android:centerColor="#c1c1c1"
    android:endColor="#4f4f4f"
    android:gradientRadius="400"
    android:startColor="#c1c1c1"
    android:type="radial" >
</gradient>

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I had the same problems, but using easy_install "module" solved the problem for me.

I am not sure why, but pip and easy_install use different install locations, and easy_install chose the right ones.

Edit: without re-checking but because of the comments; it seems that different (OSX and brew-installed) installations interfere with each other which is why they tools mentioned indeed point to different locations (since they belong to different installations). I understand that usually those tools from one install point to the same folder.

Sorting rows in a data table

Or, if you can use a DataGridView, you could just call Sort(column, direction):

namespace Sorter
{
    using System;
    using System.ComponentModel;
    using System.Windows.Forms;

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.dataGridView1.Rows.Add("Abc", 5);
            this.dataGridView1.Rows.Add("Def", 8);
            this.dataGridView1.Rows.Add("Ghi", 3);
            this.dataGridView1.Sort(this.dataGridView1.Columns[1], 
                                    ListSortDirection.Ascending);
        }
    }
}

Which would give you the desired result:

Debugger view

Renaming a directory in C#

You should move it:

Directory.Move(source, destination);

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

The CORS issue should be fixed in the backend. Temporary workaround uses this option.

  1. Go to C:\Program Files\Google\Chrome\Application

  2. Open command prompt

  3. Execute the command chrome.exe --disable-web-security --user-data-dir="c:/ChromeDevSession"

Using the above option, you can able to open new chrome without security. this chrome will not throw any cors issue.

enter image description here

Gradient borders

WebKit now (and Chrome 12 at least) supports gradients as border image:

-webkit-border-image: -webkit-gradient(linear, left top, left bottom, from(#00abeb), to(#fff), color-stop(0.5, #fff), color-stop(0.5, #66cc00)) 21 30 30 21 repeat repeat;

Prooflink -- http://www.webkit.org/blog/1424/css3-gradients/
Browser support: http://caniuse.com/#search=border-image

How to call an async method from a getter or setter?

You can always call an asynchronous method without await if you simply want to fire and forget. But it becomes tricky when you need to wait for the result and do something with the result.

I had to call an async method in a property setter in an ASP.NET Core Blazor Server Side component. I needed to get a result from that async method and do something else.

I was stuck as I could not even use the Task.Result property in Blazor context.

So, I solved the problem by calling the .ContinueWith method which worked great. Here is a sample snippet I used.

    public bool AProperty
    {
        get => _aProperty;
        set
        {
            if (_aProperty!= value)
            {
                _aProperty= value;

                myService.UpdateAReocrdAsync().ContinueWith(previousTask =>
                {
                    int numberOfRowsAffected = previousTask.Result;
                   
                    if (numberOfRowsAffected > 0)
                    {
                        toastService.ShowSuccess($"Total {numberOfRowsAffected} rows updated.");
                    }
                    else
                    {
                        toastService.ShowError("No record was updated.");
                    }
                });
            }
        }
    }

Android Camera Preview Stretched

My requirements are the camera preview need to be fullscreen and keep the aspect ratio. Hesam and Yoosuf's solution was great but I do see a high zoom problem for some reason.

The idea is the same, have the preview container center in parent and increase the width or height depend on the aspect ratios until it can cover the entire screen.

One thing to note is the preview size is in landscape because we set the display orientation.

camera.setDisplayOrientation(90);

The container that we will add the SurfaceView view to:

<RelativeLayout
    android:id="@+id/camera_preview_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"/>

Add the preview to it's container with center in parent in your activity.

this.cameraPreview = new CameraPreview(this, camera);
cameraPreviewContainer.removeAllViews();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
cameraPreviewContainer.addView(cameraPreview, 0, params);

Inside the CameraPreview class:

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (holder.getSurface() == null) {
        // preview surface does not exist
        return;
    }

    stopPreview();

    // set preview size and make any resize, rotate or
    // reformatting changes here
    try {
        Camera.Size nativePictureSize = CameraUtils.getNativeCameraPictureSize(camera);
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(optimalSize.width, optimalSize.height);
        parameters.setPictureSize(nativePictureSize.width, nativePictureSize.height);
        camera.setParameters(parameters);
        camera.setDisplayOrientation(90);
        camera.setPreviewDisplay(holder);
        camera.startPreview();

    } catch (Exception e){
        Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

    if (supportedPreviewSizes != null && optimalSize == null) {
        optimalSize = CameraUtils.getOptimalSize(supportedPreviewSizes, width, height);
        Log.i(TAG, "optimal size: " + optimalSize.width + "w, " + optimalSize.height + "h");
    }

    float previewRatio =  (float) optimalSize.height / (float) optimalSize.width;
    // previewRatio is height/width because camera preview size are in landscape.
    float measuredSizeRatio = (float) width / (float) height;

    if (previewRatio >= measuredSizeRatio) {
        measuredHeight = height;
        measuredWidth = (int) ((float)height * previewRatio);
    } else {
        measuredWidth = width;
        measuredHeight = (int) ((float)width / previewRatio);
    }
    Log.i(TAG, "Preview size: " + width + "w, " + height + "h");
    Log.i(TAG, "Preview size calculated: " + measuredWidth + "w, " + measuredHeight + "h");

    setMeasuredDimension(measuredWidth, measuredHeight);
}

this in equals method

this is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.

How to select all records from one table that do not exist in another table?

You can either do

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

or

SELECT name 
FROM table2 
WHERE NOT EXISTS 
    (SELECT * 
     FROM table1 
     WHERE table1.name = table2.name)

See this question for 3 techniques to accomplish this

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

ALTER TABLE to add a composite primary key

ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);

How to select specific form element in jQuery?

$("#name", '#form2').val("Hello World")

Best way to make a shell script daemon?

try executing using & if you save this file as program.sh

you can use

$. program.sh &

How to do error logging in CodeIgniter (PHP)

In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';

Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/

WCF Service Returning "Method Not Allowed"

Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract:

[ServiceContract]
public interface IUploadService
{
    [WebGet()]
    [OperationContract]
    string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.

    [OperationContract]
    void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.
 }

How to find out what group a given user has?

This one shows the user's uid as well as all the groups (with their gids) they belong to

id userid

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You have to add following in header:

<script type="text/javascript">
        function fixform() {
            if (opener.document.getElementById("aspnetForm").target != "_blank") return;

            opener.document.getElementById("aspnetForm").target = "";
            opener.document.getElementById("aspnetForm").action = opener.location.href;
            }
</script>

Then call fixform() in load your page.

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

How is TeamViewer so fast?

It sounds indeed like video streaming more than image streaming, as someone suggested. JPEG/PNG compression isn't targeted for these types of speeds, so forget them.

Imagine having a recording codec on your system that can realtime record an incoming video stream (your screen). A bit like Fraps perhaps. Then imagine a video playback codec on the other side (the remote client). As HD recorders can do it (record live and even playback live from the same HD), so should you, in the end. The HD surely can't deliver images quicker than you can read your display, so that isn't the bottleneck. The bottleneck are the video codecs. You'll find the encoder much more of a problem than the decoder, as all decoders are mostly free.

I'm not saying it's simple; I myself have used DirectShow to encode a video file, and it's not realtime by far. But given the right codec I'm convinced it can work.

How to stop console from closing on exit?

What about Console.Readline();?

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

The answer by josh and maleki will return true on both upper and lower case if the character or the whole string is numeric. making the result a false result. example using josh

var character = '5';
if (character == character.toUpperCase()) {
 alert ('upper case true');
}
if (character == character.toLowerCase()){
 alert ('lower case true');
}

another way is to test it first if it is numeric, else test it if upper or lower case example

var strings = 'this iS a TeSt 523 Now!';
var i=0;
var character='';
while (i <= strings.length){
    character = strings.charAt(i);
    if (!isNaN(character * 1)){
        alert('character is numeric');
    }else{
        if (character == character.toUpperCase()) {
            alert ('upper case true');
        }
        if (character == character.toLowerCase()){
            alert ('lower case true');
        }
    }
    i++;
}

How to print a query string with parameter values when using Hibernate

for development with Wildfly ( standalone.xml), add those loggers:

<logger category="org.hibernate.SQL">
   <level name="DEBUG"/>
</logger>
<logger category="org.hibernate.type.descriptor.sql">
   <level name="TRACE"/>
</logger>

How to display Woocommerce product price by ID number on a custom page?

If you have the product's ID you can use that to create a product object:

$_product = wc_get_product( $product_id );

Then from the object you can run any of WooCommerce's product methods.

$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();

Update
Please review the Codex article on how to write your own shortcode.

Integrating the WooCommerce product data might look something like this:

function so_30165014_price_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = "price = " . $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

Your shortcode would then look like [woocommerce_price id="99"]

How do I convert array of Objects into one Object in JavaScript?

_x000D_
_x000D_
// original_x000D_
var arr = [{_x000D_
    key: '11',_x000D_
    value: '1100',_x000D_
    $$hashKey: '00X'_x000D_
  },_x000D_
  {_x000D_
    key: '22',_x000D_
    value: '2200',_x000D_
    $$hashKey: '018'_x000D_
  }_x000D_
];_x000D_
_x000D_
// My solution_x000D_
var obj = {};_x000D_
for (let i = 0; i < arr.length; i++) {_x000D_
  obj[arr[i].key] = arr[i].value;_x000D_
}_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Create a string of variable length, filled with a repeated character

Based on answers from Hogan and Zero Trick Pony. I think this should be both fast and flexible enough to handle well most use cases:

var hash = '####################################################################'

function build_string(length) {  
    if (length == 0) {  
        return ''  
    } else if (hash.length <= length) {  
        return hash.substring(0, length)  
    } else {  
        var result = hash  
        const half_length = length / 2  
        while (result.length <= half_length) {  
            result += result  
        }  
        return result + result.substring(0, length - result.length)  
    }  
}  

Git command to display HEAD commit id?

git log -1

for only commit id

git log | head -n 1 

Target WSGI script cannot be loaded as Python module

I know this question is pretty old, but I wrestled with this for about eight hours just now. If you have a system with SELinux enabled and you've put your virtualenv in particular places, mod_wsgi won't be able to add your specified python-path to the site-packages. It also won't raise any errors; as it turns out the mechanism it uses to add the specified python-path to the site packages is with the Python site module, specifically site.adduserdir(). This method doesn't raise any errors if the directory is missing or can't be accessed, so mod_wsgi also doesn't raise any errors.

Anyway, try turning off SELinux with

sudo setenforce 0

or by making sure that the process you're running Apache as has the appropriate ACLs with SELinux to access the directory the virtualenv is in.

Printing tuple with string formatting in Python

Many answers given above were correct. The right way to do it is:

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

However, there was a dispute over if the '%' String operator is obsolete. As many have pointed out, it is definitely not obsolete, as the '%' String operator is easier to combine a String statement with a list data.

Example:

>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
First: 1, Second: 2, Third: 3

However, using the .format() function, you will end up with a verbose statement.

Example:

>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
>>> print 'First: {}, Second: {}, Third: {}'.format(1,2,3)
>>> print 'First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup)

First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3

Further more, '%' string operator also useful for us to validate the data type such as %s, %d, %i, while .format() only support two conversion flags: '!s' and '!r'.

How to make the HTML link activated by clicking on the <li>?

#menu li { padding: 0px; }
#menu li a { margin: 0px; display: block; width: 100%; height: 100%; }

It may need some tweaking for IE6, but that's about how you do it.

Error Code: 2013. Lost connection to MySQL server during query

I ran into this while running a stored proc- which was creating lots of rows into a table in the database. I could see the error come right after the time crossed the 30 sec boundary.

I tried all the suggestions in the other answers. I am sure some of it helped , however- what really made it work for me was switching to SequelPro from Workbench.

I am guessing it was some client side connection that I could not spot in Workbench. Maybe this will help someone else as well ?

1064 error in CREATE TABLE ... TYPE=MYISAM

As documented under CREATE TABLE Syntax:

Note
The older TYPE option was synonymous with ENGINE. TYPE was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely on TYPE to use ENGINE instead.

Therefore, you want:

CREATE TABLE dave_bannedwords(
  id   INT(11)     NOT NULL AUTO_INCREMENT,
  word VARCHAR(60) NOT NULL DEFAULT '',
  PRIMARY KEY (id),
  KEY id(id) -- this is superfluous in the presence of your PK, ergo unnecessary
) ENGINE = MyISAM ;

How to check the function's return value if true or false

you're comparing the result against a string ('false') not the built-in negative constant (false)

just use

if(ValidateForm() == false) {

or better yet

if(!ValidateForm()) {

also why are you calling validateForm twice?

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

Search for string and get count in vi editor

You need the n flag. To count words use:

:%s/\i\+/&/gn   

and a particular word:

:%s/the/&/gn        

See count-items documentation section.

If you simply type in:

%s/pattern/pattern/g

then the status line will give you the number of matches in vi as well.

How do I pass variables and data from PHP to JavaScript?

I have come out with an easy method to assign JavaScript variables using PHP.

It uses HTML5 data attributes to store PHP variables and then it's assigned to JavaScript on page load.

A complete tutorial can be found here.

Example:

<?php
    $variable_1 = "QNimate";
    $variable_2 = "QScutter";
?>
    <span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
<?php

Here is the JavaScript code

var variable_1 = undefined;
var variable_2 = undefined;

window.onload = function(){
    variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
    variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
}

What's the difference between .bashrc, .bash_profile, and .environment?

The main difference with shell config files is that some are only read by "login" shells (eg. when you login from another host, or login at the text console of a local unix machine). these are the ones called, say, .login or .profile or .zlogin (depending on which shell you're using).

Then you have config files that are read by "interactive" shells (as in, ones connected to a terminal (or pseudo-terminal in the case of, say, a terminal emulator running under a windowing system). these are the ones with names like .bashrc, .tcshrc, .zshrc, etc.

bash complicates this in that .bashrc is only read by a shell that's both interactive and non-login, so you'll find most people end up telling their .bash_profile to also read .bashrc with something like

[[ -r ~/.bashrc ]] && . ~/.bashrc

Other shells behave differently - eg with zsh, .zshrc is always read for an interactive shell, whether it's a login one or not.

The manual page for bash explains the circumstances under which each file is read. Yes, behaviour is generally consistent between machines.

.profile is simply the login script filename originally used by /bin/sh. bash, being generally backwards-compatible with /bin/sh, will read .profile if one exists.

Cache an HTTP 'Get' service response in AngularJS?

As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

Difference between a virtual function and a pure virtual function

A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.

You denote that fact by appending the "= 0" to the declaration, like this:

class AbstractBase
{
    virtual void PureVirtualFunction() = 0;
}

Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:

class Derived : public AbstractBase
{
    virtual void PureVirtualFunction() override { }
}

By adding the override keyword, the compiler will ensure that there is a base class virtual function with the same signature.

Is there a Pattern Matching Utility like GREP in Windows?

If you don't mind a paid-for product, PowerGREP is my personal favorite.

How do I use extern to share variables between source files?

Extern is the keyword you use to declare that the variable itself resides in another translation unit.

So you can decide to use a variable in a translation unit and then access it from another one, then in the second one you declare it as extern and the symbol will be resolved by the linker.

If you don't declare it as extern you'll get 2 variables named the same but not related at all, and an error of multiple definitions of the variable.

Refer to a cell in another worksheet by referencing the current worksheet's name?

Unless you want to go the VBA route to work out the Tab name, the Excel formula is fairly ugly based upon Mid functions, etc. But both these methods can be found here if you want to go that way.

Rather, the way I would do it is:

1) Make one cell on your sheet named, for example, Reference_Sheet and put in that cell the value "Jan Item" for example.

2) Now, use the Indirect function like:

=INDIRECT(Reference_Sheet&"!J3") 

3) Now, for each month's sheet, you just have to change that one Reference_Sheet cell.

Hope this gives you what you're looking for!

Java: int[] array vs int array[]

No, there is no difference. But I prefer using int[] array as it is more readable.

Multiple files upload in Codeigniter

I change upload method with images[] according to @Denmark.

    private function upload_files($path, $title, $files)
    {
        $config = array(
            'upload_path'   => $path,
            'allowed_types' => 'jpg|gif|png',
            'overwrite'     => 1,                       
        );

        $this->load->library('upload', $config);

        $images = array();

        foreach ($files['name'] as $key => $image) {
            $_FILES['images[]']['name']= $files['name'][$key];
            $_FILES['images[]']['type']= $files['type'][$key];
            $_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
            $_FILES['images[]']['error']= $files['error'][$key];
            $_FILES['images[]']['size']= $files['size'][$key];

            $fileName = $title .'_'. $image;

            $images[] = $fileName;

            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if ($this->upload->do_upload('images[]')) {
                $this->upload->data();
            } else {
                return false;
            }
        }

        return $images;
    }

List all sequences in a Postgres db 8.1 with SQL

The following query gives names of all sequences.

SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';

Typically a sequence is named as ${table}_id_seq. Simple regex pattern matching will give you the table name.

To get last value of a sequence use the following query:

SELECT last_value FROM test_id_seq;

How can I pad an int with leading zeros when using cout << operator?

cout.fill( '0' );    
cout.width( 3 );
cout << value;

Accessing a property in a parent Component

There are different way:

export class Profile implements OnInit {
constructor(@Host() parent: App) {
  parent.userStatus ...
}
  • data-binding
export class Profile implements OnInit {
  @Input() userStatus:UserStatus;
  ...
}

<profile [userStatus]="userStatus">

Detect rotation of Android phone in the browser with JavaScript

Cross browser way

$(window).on('resize orientationchange webkitfullscreenchange mozfullscreenchange fullscreenchange',  function(){
//code here
});

Using Cygwin to Compile a C program; Execution error

Compiling your C program using Cygwin

We will be using the gcc compiler on Cygwin to compile programs.

1) Launch Cygwin

2) Change to the directory you created for this class by typing

cd c:/windows/desktop

3) Compile the program by typing

gcc myProgram.c -o myProgram

the command gcc invokes the gcc compiler to compile your C program.

Change PictureBox's image to image from my resources?

Ok...so first you need to import in your project the image

1)Select the picturebox in Form Design

2)Open PictureBox Tasks (it's the little arrow pinted to right on the edge on the picturebox)

3)Click on "Choose image..."

4)Select the second option "Project resource file:" (this option will create a folder called "Resources" which you can acces with Properties.Resources)

5)Click on import and select your image from your computer (now a copy of the image with the same name as the image will be sent in Resources folder created at step 4)

6)Click on ok

Now the image is in your project and you can use it with Properties command.Just type this code when you want to change the picture from picturebox:

pictureBox1.Image = Properties.Resources.myimage;

Note: myimage represent the name of the image...after typing the dot after Resources,in your options it will be your imported image file

Javascript change color of text and background to input value

Depending on which event you actually want to use (textbox change, or button click), you can try this:

HTML:

<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>

JS:

function changeBackground(obj) {
    document.getElementById("coltext").style.color = obj.value;
}

DEMO: http://jsfiddle.net/6pLUh/

One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange allows you to change the color based on the input.

How to use nan and inf in C?

Here is a simple way to define those constants, and I'm pretty sure it's portable:

const double inf = 1.0/0.0;
const double nan = 0.0/0.0;

When I run this code:

printf("inf  = %f\n", inf);
printf("-inf = %f\n", -inf);
printf("nan  = %f\n", nan);
printf("-nan = %f\n", -nan);

I get:

inf  = inf
-inf = -inf
nan  = -nan
-nan = nan

Twitter Bootstrap hide css class and jQuery

As dfsq said i just had to use removeClass("hide") instead of toggle()

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Extending @hstoerr answer with some code:


Create LoggingRequestInterceptor to log requests responses

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

        ClientHttpResponse response = execution.execute(request, body);

        log(request,body,response);

        return response;
    }

    private void log(HttpRequest request, byte[] body, ClientHttpResponse response) throws IOException {
        //do logging
    }
}

Setup RestTemplate

RestTemplate rt = new RestTemplate();

//set interceptors/requestFactory
ClientHttpRequestInterceptor ri = new LoggingRequestInterceptor();
List<ClientHttpRequestInterceptor> ris = new ArrayList<ClientHttpRequestInterceptor>();
ris.add(ri);
rt.setInterceptors(ris);
rt.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());

How to convert date format to DD-MM-YYYY in C#

I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.

using System.Threading;

string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);

DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);

All you have to do is change the culture name, for example: "en-US" = United States "fr-FR" = French-speaking France "fr-CA" = French-speaking Canada etc...

Convert alphabet letters to number in Python

def letter_to_int(letter):
    alphabet = list('abcdefghijklmnopqrstuvwxyz')
    return alphabet.index(letter) + 1

here, the index (x) function returns the position value of x if the list contains x.

.htaccess - how to force "www." in a generic way?

I would use this rule:

RewriteEngine On
RewriteCond %{HTTP_HOST} !=""
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The first condition checks whether the Host value is not empty (in case of HTTP/1.0); the second checks whether the the Host value does not begin with www.; the third checks for HTTPS (%{HTTPS} is either on or off, so %{HTTPS}s is either ons or offs and in case of ons the s is matched). The substitution part of RewriteRule then just merges the information parts to a full URL.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The string you're trying to parse as a JSON is not encoded in UTF-8. Most likely it is encoded in ISO-8859-1. Try the following:

json.loads(unicode(opener.open(...), "ISO-8859-1"))

That will handle any umlauts that might get in the JSON message.

You should read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!). I hope that it will clarify some issues you're having around Unicode.

Subset and ggplot2

Similar to @nicolaskruchten s answer you could do the following:

require(ggplot2)

df = data.frame(ID = c('P1', 'P1', 'P2', 'P2', 'P3', 'P3'),
                Value1 = c(100, 120, 300, 400, 130, 140),
                Value2 = c(12, 13, 11, 16, 15, 12))

ggplot(df) + 
  geom_line(data = ~.x[.x$ID %in% c("P1" , "P3"), ],
            aes(Value1, Value2, group = ID, colour = ID))

Taking screenshot on Emulator from Android Studio

1.First run your Application 2.Go to Tool-->Android-->Android Device Monitor Check image for more detail

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

sql use statement with variable

Just wanted to thank KM for his valuable solution. I implemented it myself to reduce the amount of lines in a shrinkdatabase request on SQLServer. Here is my SQL request if it can help anyone :

-- Declare the variable to be used
DECLARE @Query varchar (1000)
DECLARE @MyDBN varchar(11);
-- Initializing the @MyDBN variable (possible values : db1, db2, db3, ...)
SET @MyDBN = 'db1';
-- Creating the request to execute
SET @Query='use '+ @MyDBN +'; ALTER DATABASE '+ @MyDBN +' SET RECOVERY SIMPLE WITH NO_WAIT; DBCC SHRINKDATABASE ('+ @MyDBN +', 1, TRUNCATEONLY); ALTER DATABASE '+ @MyDBN +' SET RECOVERY FULL WITH NO_WAIT'
-- 
EXEC (@Query)

Adding elements to a collection during iteration

For examle we have two lists:

  public static void main(String[] args) {
        ArrayList a = new ArrayList(Arrays.asList(new String[]{"a1", "a2", "a3","a4", "a5"}));
        ArrayList b = new ArrayList(Arrays.asList(new String[]{"b1", "b2", "b3","b4", "b5"}));
        merge(a, b);
        a.stream().map( x -> x + " ").forEach(System.out::print);
    }
   public static void merge(List a, List b){
        for (Iterator itb = b.iterator(); itb.hasNext(); ){
            for (ListIterator it = a.listIterator() ; it.hasNext() ; ){
                it.next();
                it.add(itb.next());

            }
        }

    }

a1 b1 a2 b2 a3 b3 a4 b4 a5 b5

How to get a path to a resource in a Java JAR file

The following path worked for me: classpath:/path/to/resource/in/jar

How do I implement JQuery.noConflict() ?

In addition to that, passing true to $.noConflict(true); will also restore previous (if any) global variable jQuery, so that plugins can be initialized with correct jQuery version when multiple versions are being used.

use Lodash to sort array of object by value

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

Your code could be like:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

Replace a string in a file with nodejs

You could use simple regex:

var result = fileAsString.replace(/string to be replaced/g, 'replacement');

So...

var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/string to be replaced/g, 'replacement');

  fs.writeFile(someFile, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});

Oracle: If Table Exists

I prefer following economic solution

BEGIN
    FOR i IN (SELECT NULL FROM USER_OBJECTS WHERE OBJECT_TYPE = 'TABLE' AND OBJECT_NAME = 'TABLE_NAME') LOOP
            EXECUTE IMMEDIATE 'DROP TABLE TABLE_NAME';
    END LOOP;
END;

Php multiple delimiters in explode

Try about using:

$output = preg_split('/ (@|vs) /', $input);

Appending HTML string to the DOM

Why is that not acceptable?

document.getElementById('test').innerHTML += str

would be the textbook way of doing it.

Can you use if/else conditions in CSS?

You can use calc() in combination with var() to sort of mimic conditionals:

:root {
--var-eq-two: 0;
}

.var-eq-two {
    --var-eq-two: 1;
}

.block {
    background-position: calc(
        150px * var(--var-eq-two) +
        4px * (1 - var(--var-eq-two))
    ) 8px;
}

concept

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

Rails: How can I rename a database column in a Ruby on Rails migration?

Update - A close cousin of create_table is change_table, used for changing existing tables. It is used in a similar fashion to create_table but the object yielded to the block knows more tricks. For example:

class ChangeBadColumnNames < ActiveRecord::Migration
  def change
    change_table :your_table_name do |t|
      t.rename :old_column_name, :new_column_name
    end
  end
end

This way is more efficient if we do with other alter methods such as: remove/add index/remove index/add column, eg we can do further like:

# Rename
t.rename :old_column_name, :new_column_name
# Add column
t.string :new_column
# Remove column
t.remove :removing_column
# Index column
t.index :indexing_column
#...

Split files using tar, gz, zip, or bzip2

If you are splitting from Linux, you can still reassemble in Windows.

copy /b file1 + file2 + file3 + file4 filetogether

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

jquery how to use multiple ajax calls one after the end of the other

You could also use jquery when and then functions. for example

 $.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  //another ajax call
});

https://api.jquery.com/jQuery.when/

Making an asynchronous task in Flask

I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).

app.py:

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Run your Flask app, and start another process to run your celery worker.

$ celery worker -A app.celery --loglevel=debug

I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.

Define a struct inside a class in C++

Something like:

class Tree {

 struct node {
   int data;
   node *llink;
   node *rlink;
 };
 .....
 .....
 .....
};

Owl Carousel Won't Autoplay

If you using v1.3.3 then use following property

autoPlay : 5000

Or using latest version then use following property

autoPlay : true

In Java, remove empty elements from a list of Strings

Going to drop this lil nugget in here:

Stream.of("", "Hi", null, "How", "are", "you")
  .filter(t -> !Strings.isNullOrEmpty(t))
  .collect(ImmutableList.toImmutableList());

I wish with all of my heart that Java had a filterNot.

Hashing a string with Sha256

public static string ComputeSHA256Hash(string text)
{
    using (var sha256 = new SHA256Managed())
    {
        return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
    }                
}

The reason why you get different results is because you don't use the same string encoding. The link you put for the on-line web site that computes SHA256 uses UTF8 Encoding, while in your example you used Unicode Encoding. They are two different encodings, so you don't get the same result. With the example above you get the same SHA256 hash of the linked web site. You need to use the same encoding also in PHP.

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

Replace a newline in TSQL

I may be a year late to the party, but I work on queries & MS-SQL every day, and I got tired of the built-in functions LTRIM() & RTRIM() (and always having to call them together), and of not catching 'dirty' data that had newlines at the end, so I decided it was high time to implement a better TRIM function. I'd welcome peer feedback!

Disclaimer: this actually removes (replaces with a single whitespace) extended forms of whitespace (tab, line-feed, carriage-return, etc.), so it's been renamed as "CleanAndTrim" from my original answer. The idea here is that your string doesn't need such extra special-whitespace characters inside it, and so if they don't occur at the head/tail, they should be replaced with a plain space. If you purposefully stored such characters in your string (say, your column of data that you're about to run this on), DON'T DO IT! Improve this function or write your own that literally just removes those characters from the endpoints of the string, not from the 'body'.

Okay, now that the disclaimer is updated, here's the code.

-- =============================================
-- Description: TRIMs a string 'for real' - removes standard whitespace from ends,
-- and replaces ASCII-char's 9-13, which are tab, line-feed, vert tab,
-- form-feed, & carriage-return (respectively), with a whitespace
-- (and then trims that off if it's still at the beginning or end, of course).
-- =============================================
CREATE FUNCTION [fn_CleanAndTrim] (
       @Str nvarchar(max)
)
RETURNS nvarchar(max) AS
BEGIN
       DECLARE @Result nvarchar(max)

       SET @Result = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
              LTRIM(RTRIM(@Str)), CHAR(9), ' '), CHAR(10), ' '), CHAR(11), ' '), CHAR(12), ' '), CHAR(13), ' ')))

       RETURN @Result
END

Cheers!

Another Disclaimer: Your typical Windows line-break is CR+LF, so if your string contains those, you'd end up replacing them with "double" spaces.

UPDATE, 2016: A new version that gives you the option to replace those special-whitespace characters with other characters of your choice! This also includes commentary and the work-around for the Windows CR+LF pairing, i.e. replaces that specific char-pair with a single substitution.

IF OBJECT_ID('dbo.fn_CleanAndTrim') IS NULL
    EXEC ('CREATE FUNCTION dbo.fn_CleanAndTrim () RETURNS INT AS BEGIN RETURN 0 END')
GO
-- =============================================
-- Author: Nate Johnson
-- Source: http://stackoverflow.com/posts/24068265
-- Description: TRIMs a string 'for real' - removes standard whitespace from ends,
-- and replaces ASCII-char's 9-13, which are tab, line-feed, vert tab, form-feed,
-- & carriage-return (respectively), with a whitespace or specified character(s).
-- Option "@PurgeReplaceCharsAtEnds" determines whether or not to remove extra head/tail
-- replacement-chars from the string after doing the initial replacements.
-- This is only truly useful if you're replacing the special-chars with something
-- **OTHER** than a space, because plain LTRIM/RTRIM will have already removed those.
-- =============================================
ALTER FUNCTION dbo.[fn_CleanAndTrim] (
    @Str NVARCHAR(MAX)
    , @ReplaceTabWith NVARCHAR(5) = ' '
    , @ReplaceNewlineWith NVARCHAR(5) = ' '
    , @PurgeReplaceCharsAtEnds BIT = 1
)
RETURNS NVARCHAR(MAX) AS
BEGIN
    DECLARE @Result NVARCHAR(MAX)

    --The main work (trim & initial replacements)
    SET @Result = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
        LTRIM(RTRIM(@Str))  --Basic trim
        , NCHAR(9), @ReplaceTabWith), NCHAR(11), @ReplaceTabWith)   --Replace tab & vertical-tab
        , (NCHAR(13) + NCHAR(10)), @ReplaceNewlineWith) --Replace "Windows" linebreak (CR+LF)
        , NCHAR(10), @ReplaceNewlineWith), NCHAR(12), @ReplaceNewlineWith), NCHAR(13), @ReplaceNewlineWith)))   --Replace other newlines

    --If asked to trim replacement-char's from the ends & they're not both whitespaces
    IF (@PurgeReplaceCharsAtEnds = 1 AND NOT (@ReplaceTabWith = N' ' AND @ReplaceNewlineWith = N' '))
    BEGIN
        --Purge from head of string (beginning)
        WHILE (LEFT(@Result, DATALENGTH(@ReplaceTabWith)/2) = @ReplaceTabWith)
            SET @Result = SUBSTRING(@Result, DATALENGTH(@ReplaceTabWith)/2 + 1, DATALENGTH(@Result)/2)

        WHILE (LEFT(@Result, DATALENGTH(@ReplaceNewlineWith)/2) = @ReplaceNewlineWith)
            SET @Result = SUBSTRING(@Result, DATALENGTH(@ReplaceNewlineWith)/2 + 1, DATALENGTH(@Result)/2)

        --Purge from tail of string (end)
        WHILE (RIGHT(@Result, DATALENGTH(@ReplaceTabWith)/2) = @ReplaceTabWith)
            SET @Result = SUBSTRING(@Result, 1, DATALENGTH(@Result)/2 - DATALENGTH(@ReplaceTabWith)/2)

        WHILE (RIGHT(@Result, DATALENGTH(@ReplaceNewlineWith)/2) = @ReplaceNewlineWith)
            SET @Result = SUBSTRING(@Result, 1, DATALENGTH(@Result)/2 - DATALENGTH(@ReplaceNewlineWith)/2)
    END

    RETURN @Result
END
GO

Get file from project folder java

These lines worked in my case,

ClassLoader classLoader = getClass().getClassLoader();
File fi = new File(classLoader.getResource("test.txt").getFile());

provided test.txt file inside src

How to stop/shut down an elasticsearch node?

Updated answer.

_shutdown API has been removed in elasticsearch 2.x.

Some options:

  • In your terminal (dev mode basically), just type "Ctrl-C"

  • If you started it as a daemon (-d) find the PID and kill the process: SIGTERM will shut Elasticsearch down cleanly (kill -15 PID)

  • If running as a service, run something like service elasticsearch stop:

Previous answer. It's now deprecated from 1.6.

Yeah. See admin cluster nodes shutdown documentation

Basically:

# Shutdown local node
$ curl -XPOST 'http://localhost:9200/_cluster/nodes/_local/_shutdown'

# Shutdown all nodes in the cluster
$ curl -XPOST 'http://localhost:9200/_shutdown'

update one table with data from another

Oracle 11g R2:

create table table1 (
  id number,
  name varchar2(10),
  desc_ varchar2(10)
);

create table table2 (
  id number,
  name varchar2(10),
  desc_ varchar2(10)
);

insert into table1 values(1, 'a', 'abc');
insert into table1 values(2, 'b', 'def');
insert into table1 values(3, 'c', 'ghi');

insert into table2 values(1, 'x', '123');
insert into table2 values(2, 'y', '456');

merge into table1 t1
using (select * from table2) t2
on (t1.id = t2.id)
when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;

select * from table1;

        ID NAME       DESC_
---------- ---------- ----------
         1 x          123
         2 y          456
         3 c          ghi

See also Oracle - Update statement with inner join.

AJAX cross domain call

You will need to dynamically insert a script tag into the page that references the data. Using JSONP, you can execute some callback function when the script has loaded.

The wikipedia page on JSONP has a concise example; the script tag:

<script type="text/javascript" src="http://domain1.com/getjson?jsonp=parseResponse">
</script>

would return the JSON data wrapped in a call to parseResponse:

parseResponse({"Name": "Cheeso", "Rank": 7})

(depending on the configuration of the getjson script on domain1.com)

The code to insert the tag dynamically would be something like:

var s = document.createElement("script");
s.src = "http://domain1.com/getjson?jsonp=parseResponse";
s.type = "text/javascript";
document.appendChild(s);

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

Did encounter the same problem as I was trying to compile a maven project set to 1.7 on a windows 10 environment running JAVA = 1.8.

I resolved it by changing the java version from 1.7 to 1.8 as shown below.

 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
    </configuration>
  </plugin>

How to use graphics.h in codeblocks?

AFAIK, in the epic DOS era there is a header file named graphics.h shipped with Borland Turbo C++ suite. If it is true, then you are out of luck because we're now in Windows era.

What is the difference between Serialization and Marshaling?

Think of them as synonyms, both have a producer that sends stuff over to a consumer... In the end fields of instances are written into a byte stream and the other end foes the reverse ands up with the same instances.

NB - java RMI also contains support for transporting classes that are missing from the recipient...

What is an .inc and why use it?

It's just a way for the developer to be able to easily identify files which are meant to be used as includes. It's a popular convention. It does not have any special meaning to PHP, and won't change the behaviour of PHP or the script itself.

How can I force component to re-render with hooks in React?

As the others have mentioned, useState works - here is how mobx-react-lite implements updates - you could do something similar.

Define a new hook, useForceUpdate -

import { useState, useCallback } from 'react'

export function useForceUpdate() {
  const [, setTick] = useState(0);
  const update = useCallback(() => {
    setTick(tick => tick + 1);
  }, [])
  return update;
}

and use it in a component -

const forceUpdate = useForceUpdate();
if (...) {
  forceUpdate(); // force re-render
}

See https://github.com/mobxjs/mobx-react-lite/blob/master/src/utils.ts and https://github.com/mobxjs/mobx-react-lite/blob/master/src/useObserver.ts

How to get whole and decimal part of a number?

This is the way which I use:

$float = 4.3;    

$dec = ltrim(($float - floor($float)),"0."); // result .3

Convert or extract TTC font to TTF - how to?

This is what worked for me for extracting TTFs from .dfont and .ttc files from Mac OS X: http://transfonter.org/ttc-unpack

The resulting TTFs work fine in Windows 7.

Convert a JSON String to a HashMap

This is an old question and maybe still relate to someone.
Let's say you have string HashMap hash and JsonObject jsonObject.

1) Define key-list.
Example:

ArrayList<String> keyArrayList = new ArrayList<>();  
keyArrayList.add("key0");   
keyArrayList.add("key1");  

2) Create foreach loop, add hash from jsonObject with:

for(String key : keyArrayList){  
    hash.put(key, jsonObject.getString(key));
}

That's my approach, hope it answer the question.

@Value annotation type casting to Integer from String

This problem also occurs when you have 2 resources with the same file name; say "configurations.properties" within 2 different jar or directory path configured within the classpath. For example:

You have your "configurations.properties" in your process or web application (jar, war or ear). But another dependency (jar) have the same file "configurations.properties" in the same path. Then I suppose that Spring have no idea (@_@?) where to get the property and just sends the property name declared within the @Value annotation.

Is there an R function for finding the index of an element in a vector?

A small note about the efficiency of abovementioned methods:

 library(microbenchmark)

  microbenchmark(
    which("Feb" == month.abb)[[1]],
    which(month.abb %in% "Feb"))

  Unit: nanoseconds
   min     lq    mean median     uq  max neval
   891  979.0 1098.00   1031 1135.5 3693   100
   1052 1175.5 1339.74   1235 1390.0 7399  100

So, the best one is

    which("Feb" == month.abb)[[1]]

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

What is the difference between printf() and puts() in C?

In my experience, printf() hauls in more code than puts() regardless of the format string.

If I don't need the formatting, I don't use printf. However, fwrite to stdout works a lot faster than puts.

static const char my_text[] = "Using fwrite.\n";
fwrite(my_text, 1, sizeof(my_text) - sizeof('\0'), stdout);

Note: per comments, '\0' is an integer constant. The correct expression should be sizeof(char) as indicated by the comments.

How to cast the size_t to double or int C++

If your code is prepared to deal with overflow errors, you can throw an exception if data is too large.

size_t data = 99999999;
if ( data > INT_MAX )
{
   throw std::overflow_error("data is larger than INT_MAX");
}
int convertData = static_cast<int>(data);

Display PDF within web browser

The simplest way is to create an iframe and set the source to the URL of the PDF.

(ducks mad HTML designers) Done it myself, works fine, cross browser (crawls into bunker).

How do I create an empty array/matrix in NumPy?

For creating an empty NumPy array without defining its shape:

  1. arr = np.array([])
    

    (this is preferred, because you know you will be using this as a NumPy array)

  2.  arr = []   # and use it as NumPy array later by converting it
     arr = np.asarray(arr)
    

NumPy converts this to np.ndarray type afterward, without extra [] 'dimension'.

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

3 Steps you can follow

  1. chmod -R 775 <repo path>  
    ---> change permissions of repository
    
  2. chown -R apache:apache <repo path>  
    ---> change owner of svn repository
    
  3. chcon -R -t httpd_sys_content_t <repo path>  
    ----> change SELinux security context of the svn repository
    

Remove trailing zeros

try like this

string s = "2.4200";

s = s.TrimStart('0').TrimEnd('0', '.');

and then convert that to float

How to git commit a single file/directory

For git 1.9.5 on Windows 7: "my Notes" (double quotes) corrected this issue. In my case putting the file(s) before or after the -m 'message'. made no difference; using single quotes was the problem.

What's the difference between “mod” and “remainder”?

Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:

7 % 3 = 1  // dividend % divisor = remainder

What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.

String comparison in Objective-C

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}

Do subclasses inherit private fields?

We can simply state that when a superclass is inherited, then the private members of superclass actually become private members of the subclass and cannot be further inherited or are inacessible to the objects of subclass.

C# Get/Set Syntax Usage

Assuming you have a song class (you can refer below), the traditional implementation would be like as follows

 class Song
  {
       private String author_name;
       public String setauthorname(String X) {}; //implementation goes here
       public String getauthorname() {}; //implementation goes here
  }

Now, consider this class implementation.

      class Song 
      {
            private String author_name;
            public String Author_Name
            { 
                 get { return author_name; }
                set { author_name= value; }
             }
      }

In your 'Main' class, you will wrote your code as

    class TestSong
    { 
      public static void Main(String[] Args)
      {
          Song _song = new Song(); //create an object for class 'Song'    
          _song.Author_Name = 'John Biley';
          String author = _song.Author_Name;           
          Console.WriteLine("Authorname = {0}"+author);
      }
    }

Point to be noted;

The method you set/get should be public or protected(take care) but strictly shouldnt be private.

Exception: There is already an open DataReader associated with this Connection which must be closed first

Always, always, always put disposable objects inside of using statements. I can't see how you've instantiated your DataReader but you should do it like this:

using (Connection c = ...)
{
    using (DataReader dr = ...)
    {
        //Work with dr in here.
    }
}
//Now the connection and reader have been closed and disposed.

Now, to answer your question, the reader is using the same connection as the command you're trying to ExecuteNonQuery on. You need to use a separate connection since the DataReader keeps the connection open and reads data as you need it.

Including a css file in a blade template?

include the css file into your blade template in laravel

  1. move css file into public->css folder in your laravel project.
  2. use <link rel="stylesheet" href="{{ asset('css/filename') }}">

so css is applied in a blade.php file.

Looking for simple Java in-memory cache

Try this:

import java.util.*;

public class SimpleCacheManager {

    private static SimpleCacheManager instance;
    private static Object monitor = new Object();
    private Map<String, Object> cache = Collections.synchronizedMap(new HashMap<String, Object>());

    private SimpleCacheManager() {
    }

    public void put(String cacheKey, Object value) {
        cache.put(cacheKey, value);
    }

    public Object get(String cacheKey) {
        return cache.get(cacheKey);
    }

    public void clear(String cacheKey) {
        cache.put(cacheKey, null);
    }

    public void clear() {
        cache.clear();
    }

    public static SimpleCacheManager getInstance() {
        if (instance == null) {
            synchronized (monitor) {
                if (instance == null) {
                    instance = new SimpleCacheManager();
                }
            }
        }
        return instance;
    }

}

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

How can I read user input from the console?

a = double.Parse(Console.ReadLine());

Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.

Edit:

To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.

If you'd like to perform some sort of error checking, simply do this:

if ( double.TryParse(Console.ReadLine(), out a) ) {
  Console.Writeline("Sonuç "+ a * Math.PI;); 
}
else {
  Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}

Thanks to Öyvind and abatischev for helping me refine my answer.

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

html <input type="text" /> onchange event not working

onkeyup worked for me. onkeypress doesn't trigger when pressing back space.

Making an iframe responsive

Fully responsive iFrame for situations where aspect ratio is unknown and content in the iFrame is fully responsive.

None of the above solutions worked for my need, which was to create a fully responsive iFrame that had fully responsive dynamic content inside of it. Maintaining any kind of aspect ratio was not an option.

  1. Get height of your navigation bar and any content ABOVE or BELOW the iFrame. In my case I only needed to subtract the top navbar and I wanted the iFrame to fill all the way down to the bottom of the screen.

Code:

function getWindowHeight() {
        console.log('Get Window Height Called')
        var currentWindowHeight = $(window).height()

        var iFrame = document.getElementById("myframe")
        var frameHeight = currentWindowHeight - 95

        iFrame.height = frameHeight; 

    }
//Timeout to prevent function from repeatedly firing
    var doit;
    window.onresize = function(){
      clearTimeout(doit);
      doit = setTimeout(resizedw, 100);
    };

I also created a timeout so that on resize the function wouldn't get called a million times.

How do I display the current value of an Android Preference in the Preference summary?

In Android Studio, open "root_preferences.xml", select Design mode. Select the desired EditTextPreference preference, and under "All attributes", look for the "useSimpleSummaryProvider" attribute and set it to true. It will then show the current value.

How to edit log message already committed in Subversion?

If you are using an IDE like eclipse, you can use this easy way.

Right click on the project -> Team - Show history

In that right click on the revision id for your commit and select 'Set commit properties'.

You can modify the message as you want from here.