Programs & Examples On #Weblogic8.x

The 8.x (July 2003) release of WebLogic Server, a Java EE application server suite from Oracle. It's part of their Oracle Fusion Middleware product.

How to set environment variable or system property in spring tests?

You can set the System properties as VM arguments.

If your project is a maven project then you can execute following command while running the test class:

mvn test -Dapp.url="https://stackoverflow.com"

Test class:

public class AppTest  {
@Test
public void testUrl() {
    System.out.println(System.getProperty("app.url"));
    }
}

If you want to run individual test class or method in eclipse then :

1) Go to Run -> Run Configuration

2) On left side select your Test class under the Junit section.

3) do the following :

enter image description here

Get program execution time in the shell

You can use time and subshell ():

time (
  for (( i=1; i<10000; i++ )); do
    echo 1 >/dev/null
  done
)

Or in same shell {}:

time {
  for (( i=1; i<10000; i++ )); do
    echo 1 >/dev/null
  done
}

Where to get "UTF-8" string literal in Java?

Now I use org.apache.commons.lang3.CharEncoding.UTF_8 constant from commons-lang.

hadoop No FileSystem for scheme: file

I use sbt assembly to package my project. I also meet this problem. My solution is here. Step1: add META-INF mergestrategy in your build.sbt

case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard
case PathList("META-INF", ps @ _*) => MergeStrategy.first

Step2: add hadoop-hdfs lib to build.sbt

"org.apache.hadoop" % "hadoop-hdfs" % "2.4.0"

Step3: sbt clean; sbt assembly

Hope the above information can help you.

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

import android.support.v7.widget.Toolbar;

import it into your java class

Add an object to a python list

Is your problem similar to this:

l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"

If so, you simply need to copy the objects when you store them:

import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"

The objects in question should implement a __copy__ method to copy objects. See the documentation for copy. You may also be interested in copy.deepcopy, which is there as well.

EDIT: Here's the problem:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(wM) # appends the wM object to the list
    wM.reset()           # clears  the wM object

You need to append a copy:

import copy
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(copy.copy(wM)) # appends a copy to the list
    wM.reset()                      # clears the wM object

But I'm still confused as to where wM is coming from. Won't you just be copying the same wM object over and over, except clearing it after the first time so all the rest will be empty? Or does model() modify the wM (which sounds like a terrible design flaw to me)? And why are you throwing away result?

C# ASP.NET Send Email via TLS

TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.

regular expression for Indian mobile numbers

This Worked for me

^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$

Valid Scenarios:

+91-9883443344
9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
0091 - 9883443344
7856128945
9998564723
022-24130000
080 25478965
0416-2565478
08172-268032
04512-895612
02162-240000
+91 9883443344
022-24141414

Invalid Scenarios:

WAQU9876567892
ABCD9876541212
0226-895623124
6589451235
0924645236
0222-895612
098-8956124
022-2413184

Print <div id="printarea"></div> only?

If you only want to print this div, you must use the instruction:

@media print{
    *{display:none;}
    #mydiv{display:block;}
}

Validate form field only on submit or user input

Use $dirty flag to show the error only after user interacted with the input:

<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>

If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};

Then, if all that JS inside ng-showexpression looks too much for you, you can abstract it into a separate method:

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field, validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email', 'required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

Basic example for sharing text or image with UIActivityViewController in Swift

I found this to work flawlessly if you want to share whole screen.

@IBAction func shareButton(_ sender: Any) {

    let bounds = UIScreen.main.bounds
    UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
    self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    self.present(activityViewController, animated: true, completion: nil)
}

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Python List vs. Array - when to use?

The standard library arrays are useful for binary I/O, such as translating a list of ints to a string to write to, say, a wave file. That said, as many have already noted, if you're going to do any real work then you should consider using NumPy.

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

You can get this if the client specifies "https" but the server is only running "http". So, the server isn't expecting to make a secure connection.

How to convert integer to char in C?

To convert int to char use:

int a=8;  
char c=a+'0';
printf("%c",c);       //prints 8  

To Convert char to int use:

char c='5';
int a=c-'0';
printf("%d",a);        //prints 5

How to resolve 'unrecognized selector sent to instance'?

Set flag -ObjC in Other linker Flag in your Project setting... (Not in the static library project but the project you that is using static library...) And make sure that in Project setting Configuration is set to All Configuration

How to check if object has any properties in JavaScript?

If you are willing to use lodash, you can use the some method.

_.some(obj) // returns true or false

See this small jsbin example

How to find the last day of the month from date?

    $startDate = '2011-12-01';
    $endDate = date('Y-m');
    while (true) {
        try {
            $startDateTime = new DateTime($startDate);
            $startDateTime->add(new DateInterval('P1M'));
            $startDate = $startDateTime->format('Y-m-d');
            $endTime = $startDateTime->format('Y-m-t');
            echo $startDate . ' => ' . $endTime . PHP_EOL;
            if ($startDateTime->format('Y-m') == $endDate) {
                break;
            }
        } catch (Exception $exception) {
            var_dump($exception->getMessage());
            break;
        }
    }

After testing many solutions, this works best for me.

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

What's the -practical- difference between a Bare and non-Bare repository?

The distinction between a bare and non-bare Git repository is artificial and misleading since a workspace is not part of the repository and a repository doesn't require a workspace. Strictly speaking, a Git repository includes those objects that describe the state of the repository. These objects may exist in any directory, but typically exist in the .git directory in the top-level directory of the workspace. The workspace is a directory tree that represents a particular commit in the repository, but it may exist in any directory or not at all. Environment variable $GIT_DIR links a workspace to the repository from which it originates.

Git commands git clone and git init both have options --bare that create repositories without an initial workspace. It's unfortunate that Git conflates the two separate, but related concepts of workspace and repository and then uses the confusing term bare to separate the two ideas.

Serialize JavaScript object into JSON string

    function ArrayToObject( arr ) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i){
        var name = arr[i].name;
        var value = arr[i].value;
        obj[name] = arr[i].value;
    }
    return obj;
    }

      var form_data = $('#my_form').serializeArray();
            form_data = ArrayToObject( form_data );
            form_data.action = event.target.id;
            form_data.target = event.target.dataset.event;
            console.log( form_data );
            $.post("/api/v1/control/", form_data, function( response ){
                console.log(response);
            }).done(function( response ) {
                $('#message_box').html('SUCCESS');
            })
            .fail(function(  ) { $('#message_box').html('FAIL'); })
            .always(function(  ) { /*$('#message_box').html('SUCCESS');*/ });

$(this).serialize() -- How to add a value?

Instead of

 data: $(this).serialize() + '&=NonFormValue' + NonFormValue,

you probably want

 data: $(this).serialize() + '&NonFormValue=' + NonFormValue,

You should be careful to URL-encode the value of NonFormValue if it might contain any special characters.

Autoplay an audio with HTML5 embed tag while the player is invisible

For future reference to people who find this page later you can use:

<audio controls autoplay loop hidden>
<source src="kooche.mp3" type="audio/mpeg">
<p>If you can read this, your browser does not support the audio element.</p>
</audio>

How to workaround 'FB is not defined'?

<script>  
    window.fbAsyncInit = function() {    
        FB.init({      
            appId      :'your-app-id',      
            xfbml      :true,      
            version    :'v2.1'
        });
    };
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if(d.getElementById(id)) {
            return;
        }     
        js = d.createElement(s); 
        js.id = id;     
        js.src ="// connect.facebook.net/en_US /sdk.js";     
        fjs.parentNode.insertBefore(js, fjs);
    }
    (document,'script','facebook-jssdk'));
</script> 

From the documentation: The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML tha

How to make multiple divs display in one line but still retain width?

Flex is the better way. Just try..

display: flex;

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

Wait .5 seconds before continuing code VB.net

The problem with Threading.Thread.SLeep(2000) is that it executes first in my VB.Net program. This

Imports VB = Microsoft.VisualBasic

Public Sub wait(ByVal seconds As Single)
    Static start As Single
    start = VB.Timer()
    Do While VB.Timer() < start + seconds
        System.Windows.Forms.Application.DoEvents()
    Loop
End Sub

worked flawlessly.

Google Maps v2 - set both my location and zoom in

gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(9.491327, 76.571404), 10, 30, 0)));

How to resolve TypeError: Cannot convert undefined or null to object

This is very useful to avoid errors when accessing properties of null or undefined objects.

null to undefined object

const obj = null;
const newObj = obj || undefined;
// newObj = undefined

undefined to empty object

const obj; 
const newObj = obj || {};
// newObj = {}     
// newObj.prop = undefined, but no error here

null to empty object

const obj = null;
const newObj = obj || {};
// newObj = {}  
// newObj.prop = undefined, but no error here

Cheap way to search a large text file for a string

You could do a simple find:

f = open('file.txt', 'r')
lines = f.read()
answer = lines.find('string')

A simple find will be quite a bit quicker than regex if you can get away with it.

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Device not detected in Eclipse when connected with USB cable

On a kitkat Google Nexus 7, I tired everything here, and did not succeed. The device did previously connect properly to this computer.

Then I hit settings - developer-options - Revoke USB debugging authorisations and confirmed that I really did want to revoke them.

I unplugged and plugged the USB. The tablet beeped and asked if wanted to authorise the computer for debugging. I said "Yes" and everything worked again.

How to change a string into uppercase

For questions on simple string manipulation the dir built-in function comes in handy. It gives you, among others, a list of methods of the argument, e.g., dir(s) returns a list containing upper.

How to check if a number is a power of 2

A number is a power of 2 if it contains only 1 set bit. We can use this property and the generic function countSetBits to find if a number is power of 2 or not.

This is a C++ program:

int countSetBits(int n)
{
        int c = 0;
        while(n)
        {
                c += 1;
                n  = n & (n-1);
        }
        return c;
}

bool isPowerOfTwo(int n)
{        
        return (countSetBits(n)==1);
}
int main()
{
    int i, val[] = {0,1,2,3,4,5,15,16,22,32,38,64,70};
    for(i=0; i<sizeof(val)/sizeof(val[0]); i++)
        printf("Num:%d\tSet Bits:%d\t is power of two: %d\n",val[i], countSetBits(val[i]), isPowerOfTwo(val[i]));
    return 0;
}

We dont need to check explicitly for 0 being a Power of 2, as it returns False for 0 as well.

OUTPUT

Num:0   Set Bits:0   is power of two: 0
Num:1   Set Bits:1   is power of two: 1
Num:2   Set Bits:1   is power of two: 1
Num:3   Set Bits:2   is power of two: 0
Num:4   Set Bits:1   is power of two: 1
Num:5   Set Bits:2   is power of two: 0
Num:15  Set Bits:4   is power of two: 0
Num:16  Set Bits:1   is power of two: 1
Num:22  Set Bits:3   is power of two: 0
Num:32  Set Bits:1   is power of two: 1
Num:38  Set Bits:3   is power of two: 0
Num:64  Set Bits:1   is power of two: 1
Num:70  Set Bits:3   is power of two: 0

How to detect Adblock on my website?

async function hasAdBlock() {
  try {
    await fetch("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
      method: "HEAD",
      mode: "no-cors",
    })
    return false;
  } catch(e) {
    return true;
  }
}

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

How to fix "set SameSite cookie to none" warning?

I am using both JavaScript Cookie and Java CookieUtil in my project, below settings solved my problem:

JavaScript Cookie

var d = new Date();
d.setTime(d.getTime() + (30*24*60*60*1000)); //keep cookie 30 days
var expires = "expires=" + d.toGMTString();         
document.cookie = "visitName" + "=Hailin;" + expires + ";path=/;SameSite=None;Secure"; //can set SameSite=Lax also

JAVA Cookie (set proxy_cookie_path in Nginx)

location / {
   proxy_pass http://96.xx.xx.34;
   proxy_intercept_errors on;
   #can set SameSite=None also
   proxy_cookie_path / "/;SameSite=Lax;secure";
   proxy_connect_timeout 600;
   proxy_read_timeout 600;
}

Check result in Firefox enter image description here

Read more on https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

How to style readonly attribute with CSS?

Loads of answers here, but haven't seen the one I use:

input[type="text"]:read-only { color: blue; }

Note the dash in the pseudo selector. If the input is readonly="false" it'll catch that too since this selector catches the presence of readonly regardless of the value. Technically false is invalid according to specs, but the internet is not a perfect world. If you need to cover that case, you can do this:

input[type="text"]:read-only:not([read-only="false"]) { color: blue; }

textarea works the same way:

textarea:read-only:not([read-only="false"]) { color: blue; }

Keep in mind that html now supports not only type="text", but a slew of other textual types such a number, tel, email, date, time, url, etc. Each would need to be added to the selector.

List of all unique characters in a string?

I have an idea. Why not use the ascii_lowercase constant?

For example, running the following code:

# string module, contains constant ascii_lowercase which is all the lowercase
# letters of the English alphabet
import string
# Example value of s, a string
s = 'aaabcabccd'
# Result variable to store the resulting string
result = ''
# Goes through each letter in the alphabet and checks how many times it appears.
# If a letter appears at least oce, then it is added to the result variable
for letter in string.ascii_letters:
    if s.count(letter) >= 1:
        result+=letter

# Optional three lines to convert result variable to a list for sorting
# and then back to a string
result = list(result)
result.sort()
result = ''.join(result)

print(result)

Will print 'abcd'

There you go, all duplicates removed and optionally sorted

Downgrade npm to an older version

Before doing that Download Node Js 8.11.3 from the URL: download

Open command prompt and run this:

npm install -g [email protected]

use this version this is the stable version which works along with cordova 7.1.0

for installing cordova use : • npm install -g [email protected]

• Run command

• Cordova platform remove android (if you have old android code or code is having some issue)

• Cordova platform add android : for building android app in cordova Running: Corodva run android

CSS Progress Circle

Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:

http://jsfiddle.net/maayan/byT76/

That's the basic css that enables it:

.clip1 {
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
}
.slice1 {
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,100px,200px,0px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

.clip2 
{
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0,100px,200px,0px);
}

.slice2
{
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

and the js rotates it as required.

quite easy to understand..

Hope it helps, Maayan

I am not able launch JNLP applications using "Java Web Start"?

Java web start should be enabled.
Check if javaws (Java web start is enabled for your system), Use below command in console to open java control panel.

javaws -viewer

Image for your refrence

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

parsing JSONP $http.jsonp() response in angular.js

This should work just fine for you, so long as the function jsonp_callback is visible in the global scope:

function jsonp_callback(data) {
    // returning from async callbacks is (generally) meaningless
    console.log(data.found);
}

var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";

$http.jsonp(url);

Full demo: http://jsfiddle.net/mattball/a4Rc2/ (disclaimer: I've never written any AngularJS code before)

Set keyboard caret position in html textbox

Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon @kd7's code here's what I've come up with.

Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera

Cross-browser caret positioning technique (example: moving the cursor to the END)

// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters ( Id_of_element, caretPosition_you_want)

setCaretPosition('IDHERE', 10); // example

The meat and potatoes is basically @kd7's setCaretPosition, with the biggest tweak being if (el.selectionStart || el.selectionStart === 0), in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.

In chrome the biggest issue was that just giving it .focus() wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itself el.value = el.value; before calling our function, and now it has a grasp & position with the input to use selectionStart.

function setCaretPosition(elemId, caretPos) {
    var el = document.getElementById(elemId);

    el.value = el.value;
    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}

Why is HttpClient BaseAddress not working?

Reference Resolution is described by RFC 3986 Uniform Resource Identifier (URI): Generic Syntax. And that is exactly how it supposed to work. To preserve base URI path you need to add slash at the end of the base URI and remove slash at the beginning of relative URI.

If base URI contains non-empty path, merge procedure discards it's last part (after last /). Relevant section:

5.2.3. Merge Paths

The pseudocode above refers to a "merge" routine for merging a relative-path reference with the path of the base URI. This is accomplished as follows:

  • If the base URI has a defined authority component and an empty path, then return a string consisting of "/" concatenated with the reference's path; otherwise

  • return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most "/" in the base URI path, or excluding the entire base URI path if it does not contain any "/" characters).

If relative URI starts with a slash, it is called a absolute-path relative URI. In this case merge procedure ignore all base URI path. For more information check 5.2.2. Transform References section.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

Unfortunately the web.config setting is ignored by the default JsonResult implementation. So I guess you will need to implement a custom json result to overcome this issue.

Bootstrap: Collapse other sections when one is expanded

working like a charm here for bootstrap 4>4.1.1

var myGroup = $('your-list');

myGroup.on('show.bs.collapse','.collapse', function() {
   myGroup.find('.collapse.show').collapse('hide');
});

angular-cli server - how to proxy API requests to another server?

We can find the proxy documentation for Angular-CLI over here:

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

After setting up a file called proxy.conf.json in your root folder, edit your package.json to include the proxy config on ng start. After adding "start": "ng serve --proxy-config proxy.conf.json" to your scripts, run npm start and not ng serve, because that will ignore the flag setup in your package.json.

current version of angular-cli: 1.1.0

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

It's a date format issue. In Ireland the standard date format for the 28th of March would be "28-03-2011", whereas "03/28/2011" is the standard for the USA (among many others).

How do I load a file from resource folder?

My file in the test folder could not be found even though I followed the answers. It got resolved by rebuilding the project. It seems IntelliJ did not recognize the new file automatically. Pretty nasty to find out.

How to call javascript function from code-behind

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }

How to access a mobile's camera from a web app?

You'll want to use getUserMedia to access the camera.

This tutorial outlines the basics of accessing a device camera from the browser: https://medium.com/@aBenjamin765/make-a-camera-web-app-tutorial-part-1-ec284af8dddf

Note: This works on most Android devices, and in iOS in Safari only.

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I got this error message with vs2015, ssdt 14.1.xxx, ssrs. For me I think it was something different than described above with a 2 column, same name problem. I added this report, then deleted the report, then when I tried to add the query back in the ssrs wizard I got this message, " An error occurred while the query design method was being saved :invalid object name: tablename" . where tablename was the table on the query the wizard was reading. I tried cleaning the project, I tried rebuilding the project. In my opinion Microsoft isn't completing cleaning out the report when you delete it and as long as you try to add the original query back it won't add. The way I was able to fix it was to create the ssrs report in a whole new project (obviously nothing wrong with the query) and save it off to the side. Then I reopened my original ssrs project, right clicked on Reports, then Add, then add Existing Item. The report added back in just fine with no name conflict.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

All the model fields which have definite types, those should be validated when returned to Controller. If any of the model fields are not matching with their defined type, then ModelState.IsValid will return false. Because, These errors will be added in ModelState.

Make more than one chart in same IPython Notebook cell

I don't know if this is new functionality, but this will plot on separate figures:

df.plot(y='korisnika')
df.plot(y='osiguranika')

while this will plot on the same figure: (just like the code in the op)

df.plot(y=['korisnika','osiguranika'])

I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.

Load RSA public key from file

Below is the relevant information from the link which Zaki provided.

Generate a 2048-bit RSA private key

$ openssl genrsa -out private_key.pem 2048

Convert private Key to PKCS#8 format (so Java can read it)

$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt

Output public key portion in DER format (so Java can read it)

$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der

Private key

import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;

public class PrivateKeyReader {

  public static PrivateKey get(String filename)
  throws Exception {

    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    PKCS8EncodedKeySpec spec =
      new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
  }
}

Public key

import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;

public class PublicKeyReader {

  public static PublicKey get(String filename)
    throws Exception {

    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    X509EncodedKeySpec spec =
      new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
  }
}

How to load json into my angular.js ng-model?

I use following code, found somewhere in the internet don't remember the source though.

    var allText;
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
    return JSON.parse(allText);

CFNetwork SSLHandshake failed iOS 9

iOS 9 and OSX 10.11 require TLSv1.2 SSL for all hosts you plan to request data from unless you specify exception domains in your app's Info.plist file.

The syntax for the Info.plist configuration looks like this:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow insecure HTTP requests-->
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

If your application (a third-party web browser, for instance) needs to connect to arbitrary hosts, you can configure it like this:

<key>NSAppTransportSecurity</key>
<dict>
    <!--Connect to anything (this is probably BAD)-->
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

If you're having to do this, it's probably best to update your servers to use TLSv1.2 and SSL, if they're not already doing so. This should be considered a temporary workaround.

As of today, the prerelease documentation makes no mention of any of these configuration options in any specific way. Once it does, I'll update the answer to link to the relevant documentation.

Removing highcharts.com credits link

It's said here that you should be able to add the following to your chart config:

  credits: {
    enabled: false
  },

that will remove the "Highcharts.com" text from the bottom of the chart.

WebAPI to Return XML

In my project with netcore 2.2 I use this code:

[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
    string payload = "Something";

    OkObjectResult result = Ok( payload );

    // currently result.Formatters is empty but we'd like to ensure it will be so in the future
    result.Formatters.Clear();

    // force response as xml
    result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );

    return result;
}

It forces only one action within a controller to return a xml without effect to other actions. Also this code doesn't contain neither HttpResponseMessage or StringContent or ObjectContent which are disposable objects and hence should be handled appropriately (it is especially a problem if you use any of code analyzers that reminds you about it).

Going further you could use a handy extension like this:

public static class ObjectResultExtensions
{
    public static T ForceResultAsXml<T>( this T result )
        where T : ObjectResult
    {
        result.Formatters.Clear();
        result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );

        return result;
    }
}

And your code will become like this:

[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
    string payload = "Something";

    return Ok( payload ).ForceResultAsXml();
}

In addition, this solution looks like an explicit and clean way to force return as xml and it is easy to add to your existent code.

P.S. I used fully-qualified name Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter just to avoid ambiguity.

Plot two histograms on single chart with matplotlib

You should use bins from the values returned by hist:

import numpy as np
import matplotlib.pyplot as plt

foo = np.random.normal(loc=1, size=100) # a normal distribution
bar = np.random.normal(loc=-1, size=10000) # a normal distribution

_, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
_ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)

Two matplotlib histograms with same binning

How to split strings over multiple lines in Bash?

In certain scenarios utilizing Bash's concatenation ability might be appropriate.

Example:

temp='this string is very long '
temp+='so I will separate it onto multiple lines'
echo $temp
this string is very long so I will separate it onto multiple lines

From the PARAMETERS section of the Bash Man page:

name=[value]...

...In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays) or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable's value.

How do I get the YouTube video ID from a URL?

As webstrap mentioned in a comment:

It worked if the video start with "v" and it's from youtu.be

The regex contains a little bug \??v?=? this should just be at the watch part, otherwise you would filter a 'v' if the id starts with a 'v'. so this should do the trick

/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\??v?=?))([^#\&\?]*).*/

SQL Server 2012 can't start because of a login failure

The answer to this may be identical to the problem with full blown SQL Server (NTService\MSSQLSERVER) and this is to reset the password. The ironic thing is, there is no password.

Steps are:

  • Right click on the Service in the Services mmc
  • Click Properties
  • Click on the Log On tab
  • The password fields will appear to have entries in them...
  • Blank out both Password fields
  • Click "OK"

This should re-grant access to the service and it should start up again. Weird?

NOTE: if the problem comes back after a few hours or days, then you probably have a group policy which is overriding your settings and it's coming and taking the right away again.

finding multiples of a number in Python

If this is what you are looking for -

To find all the multiples between a given number and a limit

def find_multiples(integer, limit):
    return list(range(integer,limit+1, integer))

This should return -

Test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

I would not recommend doing such a thing. As mentioned multiple times install_requires and requirements.txt are definitely not supposed to be the same list. But since there are a lot of misleading answers all around involving private internal APIs of pip, it might be worth looking at saner alternatives...

There is no need for pip to parse a requirements.txt file from a setuptools setup.py script. The setuptools project already contains all the necessary tools in its top level package pkg_resources.

It could more or less look like this:

#!/usr/bin/env python3

import pathlib

import pkg_resources
import setuptools

with pathlib.Path('requirements.txt').open() as requirements_txt:
    install_requires = [
        str(requirement)
        for requirement
        in pkg_resources.parse_requirements(requirements_txt)
    ]

setuptools.setup(
    install_requires=install_requires,
)

Notes:

Convert Iterable to Stream using Java 8 JDK

I've created this class:

public class Streams {
    /**
     * Converts Iterable to stream
     */
    public static <T> Stream<T>  streamOf(final Iterable<T> iterable) {
        return toStream(iterable, false);
    }

    /**
     * Converts Iterable to parallel stream
     */
    public static <T> Stream<T> parallelStreamOf(final Iterable<T> iterable) {
        return toStream(iterable, true);
    }

    private static <T> Stream<T> toStream(final Iterable<T> iterable, final boolean isParallel) {
        return StreamSupport.stream(iterable.spliterator(), isParallel);
    }
}

I think it's perfectly readable because you don't have to think about spliterators and booleans (isParallel).

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

Right-click on the Solution from the Visual Studio Solution Explorer click the Manage Nuget packages for solution and install the EntityFramework

Select folder dialog WPF

If you don't want to use Windows Forms nor edit manifest files, I came up with a very simple hack using WPF's SaveAs dialog for actually selecting a directory.

No using directive needed, you may simply copy-paste the code below !

It should still be very user-friendly and most people will never notice.

The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.

It is a big hack for sure, but maybe it will do the job just fine for your usage...

In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...

// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
    string path = dialog.FileName;
    // Remove fake filename from resulting path
    path = path.Replace("\\select.this.directory", "");
    path = path.Replace(".this.directory", "");
    // If user has changed the filename, create the new directory
    if (!System.IO.Directory.Exists(path)) {
        System.IO.Directory.CreateDirectory(path);
    }
    // Our final value is in path
    textbox.Text = path;
}

The only issues with this hack are :

  • Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
  • Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
  • There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...

Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

tsql returning a table from a function or store procedure

You need a special type of function known as a table valued function. Below is a somewhat long-winded example that builds a date dimension for a data warehouse. Note the returns clause that defines a table structure. You can insert anything into the table variable (@DateHierarchy in this case) that you want, including building a temporary table and copying the contents into it.

if object_id ('ods.uf_DateHierarchy') is not null
    drop function ods.uf_DateHierarchy
go

create function ods.uf_DateHierarchy (
       @DateFrom datetime
      ,@DateTo   datetime
) returns @DateHierarchy table (
        DateKey           datetime
       ,DisplayDate       varchar (20)
       ,SemanticDate      datetime
       ,MonthKey          int     
       ,DisplayMonth      varchar (10)
       ,FirstDayOfMonth   datetime
       ,QuarterKey        int
       ,DisplayQuarter    varchar (10)
       ,FirstDayOfQuarter datetime
       ,YearKey           int
       ,DisplayYear       varchar (10)
       ,FirstDayOfYear    datetime
) as begin
    declare @year            int
           ,@quarter         int
           ,@month           int
           ,@day             int
           ,@m1ofqtr         int
           ,@DisplayDate     varchar (20)
           ,@DisplayQuarter  varchar (10)
           ,@DisplayMonth    varchar (10)
           ,@DisplayYear     varchar (10)
           ,@today           datetime
           ,@MonthKey        int
           ,@QuarterKey      int
           ,@YearKey         int
           ,@SemanticDate    datetime
           ,@FirstOfMonth    datetime
           ,@FirstOfQuarter  datetime
           ,@FirstOfYear     datetime
           ,@MStr            varchar (2)
           ,@QStr            varchar (2)
           ,@Ystr            varchar (4)
           ,@DStr            varchar (2)
           ,@DateStr         varchar (10)


    -- === Previous ===================================================
    -- Special placeholder date of 1/1/1800 used to denote 'previous'
    -- so that naive date calculations sort and compare in a sensible
    -- order.
    --
    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '1800-01-01'
        ,'Previous'
        ,'1800-01-01'
        ,180001
        ,'Prev'
        ,'1800-01-01'
        ,18001
        ,'Prev'
        ,'1800-01-01'
        ,1800
        ,'Prev'
        ,'1800-01-01'
    )

    -- === Calendar Dates =============================================
    -- These are generated from the date range specified in the input
    -- parameters.
    --
    set @today = @Datefrom
    while @today <= @DateTo begin

        set @year = datepart (yyyy, @today)
        set @month = datepart (mm, @today)
        set @day = datepart (dd, @today)
        set @quarter = case when @month in (1,2,3) then 1
                            when @month in (4,5,6) then 2
                            when @month in (7,8,9) then 3
                            when @month in (10,11,12) then 4
                        end
        set @m1ofqtr = @quarter * 3 - 2 

        set @DisplayDate = left (convert (varchar, @today, 113), 11)
        set @SemanticDate = @today
        set @MonthKey = @year * 100 + @month
        set @DisplayMonth = substring (convert (varchar, @today, 113), 4, 8)
        set @Mstr = right ('0' + convert (varchar, @month), 2)
        set @Dstr = right ('0' + convert (varchar, @day), 2)
        set @Ystr = convert (varchar, @year)
        set @DateStr = @Ystr + '-' + @Mstr + '-01'
        set @FirstOfMonth = convert (datetime, @DateStr, 120)
        set @QuarterKey = @year * 10 + @quarter
        set @DisplayQuarter = 'Q' + convert (varchar, @quarter) + ' ' +
                                    convert (varchar, @year)
        set @QStr = right ('0' + convert (varchar, @m1ofqtr), 2)   
        set @DateStr = @Ystr + '-' + @Qstr + '-01' 
        set @FirstOfQuarter = convert (datetime, @DateStr, 120)
        set @YearKey = @year
        set @DisplayYear = convert (varchar, @year)
        set @DateStr = @Ystr + '-01-01'
        set @FirstOfYear = convert (datetime, @DateStr)


        insert @DateHierarchy (
             DateKey
            ,DisplayDate
            ,SemanticDate
            ,MonthKey
            ,DisplayMonth
            ,FirstDayOfMonth
            ,QuarterKey
            ,DisplayQuarter
            ,FirstDayOfQuarter
            ,YearKey
            ,DisplayYear
            ,FirstDayOfYear
        ) values (
             @today
            ,@DisplayDate
            ,@SemanticDate
            ,@Monthkey
            ,@DisplayMonth
            ,@FirstOfMonth
            ,@QuarterKey
            ,@DisplayQuarter
            ,@FirstOfQuarter
            ,@YearKey
            ,@DisplayYear
            ,@FirstOfYear
        )

        set @today = dateadd (dd, 1, @today)
    end

    -- === Specials ===================================================
    -- 'Ongoing', 'Error' and 'Not Recorded' set two years apart to
    -- avoid accidental collisions on 'Next Year' calculations.
    --
    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9000-01-01'
        ,'Ongoing'
        ,'9000-01-01'
        ,900001
        ,'Ong.'
        ,'9000-01-01'
        ,90001
        ,'Ong.'
        ,'9000-01-01'
        ,9000
        ,'Ong.'
        ,'9000-01-01'
    )

    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9100-01-01'
        ,'Error'
        ,null
        ,910001
        ,'Error'
        ,null
        ,91001
        ,'Error'
        ,null
        ,9100
        ,'Err'
        ,null
    )

    insert @DateHierarchy (
         DateKey
        ,DisplayDate
        ,SemanticDate
        ,MonthKey
        ,DisplayMonth
        ,FirstDayOfMonth
        ,QuarterKey
        ,DisplayQuarter
        ,FirstDayOfQuarter
        ,YearKey
        ,DisplayYear
        ,FirstDayOfYear
    ) values (
         '9200-01-01'
        ,'Not Recorded'
        ,null
        ,920001
        ,'N/R'
        ,null
        ,92001
        ,'N/R'
        ,null
        ,9200
        ,'N/R'
        ,null
    )

    return
end

go

curl usage to get header

curl --head https://www.example.net

I was pointed to this by curl itself; when I issued the command with -X HEAD, it printed:

Warning: Setting custom HTTP method to HEAD with -X/--request may not work the 
Warning: way you want. Consider using -I/--head instead.

How to convert string values from a dictionary, into int/float datatypes?

  newlist=[]                       #make an empty list
  for i in list:                   # loop to hv a dict in list  
     s={}                          # make an empty dict to store new dict data 
     for k in i.keys():            # to get keys in the dict of the list 
         s[k]=int(i[k])        # change the values from string to int by int func
     newlist.append(s)             # to add the new dict with integer to the list

INNER JOIN ON vs WHERE clause

I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

Rebuild all indexes in a Database

DECLARE @Database NVARCHAR(255)   
DECLARE @Table NVARCHAR(255)  
DECLARE @cmd NVARCHAR(1000)  

DECLARE DatabaseCursor CURSOR READ_ONLY FOR  
SELECT name FROM master.sys.databases   
WHERE name NOT IN ('master','msdb','tempdb','model','distribution')  -- databases to exclude
--WHERE name IN ('DB1', 'DB2') -- use this to select specific databases and comment out line above
AND state = 0 -- database is online
AND is_in_standby = 0 -- database is not read only for log shipping
ORDER BY 1  

OPEN DatabaseCursor  

FETCH NEXT FROM DatabaseCursor INTO @Database  
WHILE @@FETCH_STATUS = 0  
BEGIN  

   SET @cmd = 'DECLARE TableCursor CURSOR READ_ONLY FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +  
   table_name + '']'' as tableName FROM [' + @Database + '].INFORMATION_SCHEMA.TABLES WHERE table_type = ''BASE TABLE'''   

   -- create table cursor  
   EXEC (@cmd)  
   OPEN TableCursor   

   FETCH NEXT FROM TableCursor INTO @Table   
   WHILE @@FETCH_STATUS = 0   
   BEGIN
      BEGIN TRY   
         SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD' 
         --PRINT @cmd -- uncomment if you want to see commands
         EXEC (@cmd) 
      END TRY
      BEGIN CATCH
         PRINT '---'
         PRINT @cmd
         PRINT ERROR_MESSAGE() 
         PRINT '---'
      END CATCH

      FETCH NEXT FROM TableCursor INTO @Table   
   END   

   CLOSE TableCursor   
   DEALLOCATE TableCursor  

   FETCH NEXT FROM DatabaseCursor INTO @Database  
END  
CLOSE DatabaseCursor   
DEALLOCATE DatabaseCursor

Can't compare naive and aware datetime.now() <= challenge.datetime_end

datetime.datetime.now is not timezone aware.

Django comes with a helper for this, which requires pytz

from django.utils import timezone
now = timezone.now()

You should be able to compare now to challenge.datetime_start

build maven project with propriatery libraries included

1 Either you can include that jar in your classpath of application
2 you can install particular jar file in your maven reopos by

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
    -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

Change HTML email body font type and size in VBA

I did a little research and was able to write this code:

strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today.  All assigned firms are complete.  Please feel free to respond with any questions.<p>Thank you.</BODY>"

apparently by setting the "font-size=11pt" instead of setting the font size <font size=5>, It allows you to select a specific font size like you normally would in a text editor, as opposed to selecting a value from 1-7 like my code was originally.

This link from simpLE MAn gave me some good info.

Adding subscribers to a list using Mailchimp's API v3

If it helps anyone, here is what I got working in Python using the Python Requests library instead of CURL.

As explained by @staypuftman above, you will need your API Key and List ID from MailChimp and make sure your API Key suffix and URL prefix (i.e. us5) match.

Python:

#########################################################################################
# To add a single contact to MailChimp (using MailChimp v3.0 API), requires:
#   + MailChimp API Key
#   + MailChimp List Id for specific list
#   + MailChimp API URL for adding a single new contact
#
# Note: the API URL has a 3/4 character location subdomain at the front of the URL string. 
# It can vary depending on where you are in the world. To determine yours, check the last 
# 3/4 characters of your API key. The API URL location subdomain must match API Key 
# suffix e.g. us5, us13, us19 etc. but in this example, us5.
# (suggest you put the following 3 values in 'settings' or 'secrets' file)
#########################################################################################
MAILCHIMP_API_KEY = 'your-api-key-here-us5'
MAILCHIMP_LIST_ID = 'your-list-id-here'
MAILCHIMP_ADD_CONTACT_TO_LIST_URL = 'https://us5.api.mailchimp.com/3.0/lists/' + MAILCHIMP_LIST_ID + '/members/'

    # Create new contact data and convert into JSON as this is what MailChimp expects in the API
    # I've hardcoded some test data but use what you get from your form as appropriate
    new_contact_data_dict = {
        "email_address": "[email protected]",              # 'email_address' is a mandatory field
        "status": "subscribed",                           # 'status' is a mandatory field
        "merge_fields": {                                 # 'merge_fields' are optional:
            "FNAME": "John",                  
            "LNAME": "Smith"
        }
    }
    new_contact_data_json = json.dumps(new_contact_data_dict)

    # Create the new contact using MailChimp API using Python 'Requests' library
    req = requests.post(
        MAILCHIMP_ADD_CONTACT_TO_LIST_URL,
        data=new_contact_data_json,
        auth=('user', MAILCHIMP_API_KEY),
        headers={"content-type": "application/json"}
    )

    # debug info if required - .text and .json also list the 'merge_fields' names for use in contact JSON above
    # print req.status_code
    # print req.text
    # print req.json()

    if req.status_code == 200:
        # success - do anything you need to do
    else:
        # fail - do anything you need to do - but here is a useful debug message
        mailchimp_fail = 'MailChimp call failed calling this URL: {0}\n' \
                         'Returned this HTTP status code: {1}\n' \
                         'Returned this response text: {2}' \
                         .format(req.url, str(req.status_code), req.text)

How do I read the source code of shell commands?

    cd ~ && apt-get source coreutils && ls -d coreutils*     

You should be able to use a command like this on ubuntu to gather the source for a package, you can omit sudo assuming your downloading to a location you own.

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

convert a list of objects from one type to another using lambda expression

If the types can be directly cast this is the cleanest way to do it:

var target = yourList.ConvertAll(x => (TargetType)x);

If the types can't be directly cast then you can map the properties from the orginal type to the target type.

var target = yourList.ConvertAll(x => new TargetType { SomeValue = x.SomeValue });

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

i must recommend a library: Moment

code:

var target12 = '2016-12-08 9:32:45 PM';
console.log(moment(target12, 'YYYY-MM-DD h:m:s A').format('YYYY-MM-DD HH:mm:ss'));

How can I insert values into a table, using a subquery with more than one result?

INSERT INTO prices (group, id, price)
  SELECT 7, articleId, 1.50 FROM article WHERE name LIKE 'ABC%'

"Please provide a valid cache path" error in laravel

Please run in terminal,

   sudo mkdir storage/framework
   sudo mkdir storage/framework/sessions
   sudo mkdir storage/framework/views
   sudo mkdir storage/framework/cache
   sudo mkdir storage/framework/cache/data

Now you have to change permission,

   sudo chmod -R 777 storage

Why does modern Perl avoid UTF-8 by default?

There's a truly horrifying amount of ancient code out there in the wild, much of it in the form of common CPAN modules. I've found I have to be fairly careful enabling Unicode if I use external modules that might be affected by it, and am still trying to identify and fix some Unicode-related failures in several Perl scripts I use regularly (in particular, iTiVo fails badly on anything that's not 7-bit ASCII due to transcoding issues).

IntelliJ does not show 'Class' when we right click and select 'New'

The directory or one of the parent directories must be marked as Source Root (In this case, it appears in blue).

If this is not the case, right click your root source directory -> Mark As -> Source Root.

How can you create pop up messages in a batch script?

Few more ways (in all of them the script waits for button pressing unlike msg.exe).

1) The geekiest and hackiest - it uses the IEXPRESS to create small exe that will create a pop-up with a single button (it can create two more types of pop-up messages).Works on EVERY windows from XP and above:

;@echo off
;setlocal

;set ppopup_executable=popupe.exe
;set "message2=click OK to continue"
;
;del /q /f %tmp%\yes >nul 2>&1
;
;copy /y "%~f0" "%temp%\popup.sed" >nul 2>&1

;(echo(FinishMessage=%message2%)>>"%temp%\popup.sed";
;(echo(TargetName=%cd%\%ppopup_executable%)>>"%temp%\popup.sed";
;(echo(FriendlyName=%message1_title%)>>"%temp%\popup.sed"
;
;iexpress /n /q /m %temp%\popup.sed
;%ppopup_executable%
;rem del /q /f %ppopup_executable% >nul 2>&1

;pause

;endlocal
;exit /b 0


[Version]
Class=IEXPRESS
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=1
HideExtractAnimation=1
UseLongFileName=0
InsideCompressed=0
CAB_FixedSize=0
CAB_ResvCodeSigning=0
RebootMode=N
InstallPrompt=%InstallPrompt%
DisplayLicense=%DisplayLicense%
FinishMessage=%FinishMessage%
TargetName=%TargetName%
FriendlyName=%FriendlyName%
AppLaunched=%AppLaunched%
PostInstallCmd=%PostInstallCmd%
AdminQuietInstCmd=%AdminQuietInstCmd%
UserQuietInstCmd=%UserQuietInstCmd%
SourceFiles=SourceFiles
[SourceFiles]
SourceFiles0=C:\Windows\System32\
[SourceFiles0]
%FILE0%=


[Strings]
AppLaunched=subst.exe
PostInstallCmd=<None>
AdminQuietInstCmd=
UserQuietInstCmd=
FILE0="subst.exe"
DisplayLicense=
InstallPrompt=

2) Using MSHTA. Also works on every windows machine from XP and above (despite yhe OP do not wants "external" languages the jsvascript here is minimized).Should be saved as .bat:

@if (true == false) @end /*!
@echo off
mshta "about:<script src='file://%~f0'></script><script>close()</script>" %*
goto :EOF */

alert("Hello, world!");

or in one line:

mshta "about:<script>alert('Hello, world!');close()</script>"

or

mshta "javascript:alert('message');close()"

or

mshta.exe vbscript:Execute("msgbox ""message"",0,""title"":close")

3) Here's parametrized .bat/jscript hybrid (should be saved as bat) .It again uses jscript despite the OP request but as it is a bat it can be called as a bat file without worries.It uses POPUP which allows a little bit more control than the more populae MSGBOX.It uses WSH ,but not MSHTA like in the example above.

 @if (@x)==(@y) @end /***** jscript comment ******
     @echo off

     cscript //E:JScript //nologo "%~f0" "%~nx0" %*
     exit /b 0

 @if (@x)==(@y) @end ******  end comment *********/


var wshShell = WScript.CreateObject("WScript.Shell");
var args=WScript.Arguments;
var title=args.Item(0);

var timeout=-1;
var pressed_message="button pressed";
var timeout_message="timedout";
var message="";

function printHelp() {
    WScript.Echo(title + "[-title Title] [-timeout m] [-tom \"Time-out message\"] [-pbm \"Pressed button message\"]  [-message \"pop-up message\"]");
}

if (WScript.Arguments.Length==1){
    runPopup();
    WScript.Quit(0);
}

if (args.Item(1).toLowerCase() == "-help" ||  args.Item(1).toLowerCase() == "-h" ) {
    printHelp();
    WScript.Quit(0);
}

if (WScript.Arguments.Length % 2 == 0 ) {
    WScript.Echo("Illegal arguments ");
    printHelp();
    WScript.Quit(1);
}

for (var arg = 1 ; arg<args.Length;arg=arg+2) {

    if (args.Item(arg).toLowerCase() == "-title") {
        title = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-timeout") {
        timeout = parseInt(args.Item(arg+1));
        if (isNaN(timeout)) {
            timeout=-1;
        }
    }

    if (args.Item(arg).toLowerCase() == "-tom") {
        timeout_message = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-pbm") {
        pressed_message = args.Item(arg+1);
    }

    if (args.Item(arg).toLowerCase() == "-message") {
        message = args.Item(arg+1);
    }
}

function runPopup(){
    var btn = wshShell.Popup(message, timeout, title, 0x0 + 0x10);

    switch(btn) {
        // button pressed.
        case 1:
            WScript.Echo(pressed_message);
            break;

        // Timed out.
        case -1:
           WScript.Echo(timeout_message);
           break;
    }
}

runPopup();

4) and one jscript.net/.bat hybrid (should be saved as .bat) .This time it uses .NET and compiles a small .exe file that could be deleted:

@if (@X)==(@Y) @end /****** silent jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal


::if exist "%~n0.exe" goto :skip_compilation

:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop



call %jsc% /nologo /out:"%~n0.exe" "%~f0" 
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

::
::::::::::
"%~n0.exe" %*
::::::::
::
endlocal
exit /b 0

****** end of jscript comment ******/

import System;
import System.WIndows;
import System.Windows.Forms

var arguments:String[] = Environment.GetCommandLineArgs();
MessageBox.Show(arguments[1],arguments[0]);

5) and at the end one single call to powershell that creates a pop-up (can be called from command line or from batch if powershell is installed):

powershell [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Hello World""", """My PopUp Message Box""")

6) Though msg solution is already post as answer here's a better way to be used:

msg * /self /w "hello world"

/self is a not documented switch that will force msg to send the message only to the current user.

What is String pool in Java?

When the JVM loads classes, or otherwise sees a literal string, or some code interns a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like

String s = "test";
return (s == "test");

it'll return true, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals, as there's a single reference comparison rather than a bunch of char comparisons.

You can add a string to the pool by calling String.intern(), which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern) will be equal to any identical literal. For example:

String s1 = "test";
String s2 = new String("test");  // "new String" guarantees a different object

System.out.println(s1 == s2);  // should print "false"

s2 = s2.intern();
System.out.println(s1 == s2);  // should print "true"

what innerHTML is doing in javascript?

Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.

However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.

Remove a HTML tag but keep the innerHtml

Behold, for the simplest answer is mind blowing:

outerHTML is supported down to Internet Explorer 4 !

Here is to do it with javascript even without jQuery

element.outerHTML = element.innerHTML

with jQuery element = $('b')[0]; or without jQuery element = document.querySelector('b');

If you want it as a function:

function unwrap(selector) {
    var nodelist = document.querySelectorAll(selector);
    Array.prototype.forEach.call(nodelist, function(item,i){
        item.outerHTML = item.innerHTML; // or item.innerText if you want to remove all inner html tags 
    })
}

unwrap('b')

This should work in all major browser including old IE. in recent browser, we can even call forEach right on the nodelist.

function unwrap(selector) {
    document.querySelectorAll('b').forEach( (item,i) => {
        item.outerHTML = item.innerText;
    } )
}

Change package name for Android in React Native

The init script generates a unique identifier for Android based on the name you gave it (e.g. com.acmeapp for AcmeApp).

You can see what name was generated by looking for the applicationId key in android/app/build.gradle.

If you need to change that unique identifier, do it now as described below:

In the /android folder, replace all occurrences of com.acmeapp by com.acme.app

Then change the directory structure with the following commands:

mkdir android/app/src/main/java/com/acme

mv android/app/src/main/java/com/acmeapp android/app/src/main/java/com/acme/app

You need a folder level for each dot in the app identifier.

Source: https://blog.elao.com/en/dev/from-react-native-init-to-app-stores-real-quick/

How do I space out the child elements of a StackPanel?

Following up on Sergey's suggestion, you can define and reuse a whole Style (with various property setters, including Margin) instead of just a Thickness object:

<Style x:Key="MyStyle" TargetType="SomeItemType">
  <Setter Property="Margin" Value="0,5,0,5" />
  ...
</Style>

...

  <StackPanel>
    <StackPanel.Resources>
      <Style TargetType="SomeItemType" BasedOn="{StaticResource MyStyle}" />
    </StackPanel.Resources>
  ...
  </StackPanel>

Note that the trick here is the use of Style Inheritance for the implicit style, inheriting from the style in some outer (probably merged from external XAML file) resource dictionary.

Sidenote:

At first, I naively tried to use the implicit style to set the Style property of the control to that outer Style resource (say defined with the key "MyStyle"):

<StackPanel>
  <StackPanel.Resources>
    <Style TargetType="SomeItemType">
      <Setter Property="Style" Value={StaticResource MyStyle}" />
    </Style>
  </StackPanel.Resources>
</StackPanel>

which caused Visual Studio 2010 to shut down immediately with CATASTROPHIC FAILURE error (HRESULT: 0x8000FFFF (E_UNEXPECTED)), as described at https://connect.microsoft.com/VisualStudio/feedback/details/753211/xaml-editor-window-fails-with-catastrophic-failure-when-a-style-tries-to-set-style-property#

List all environment variables from the command line

Simply run set from cmd.

Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings.

What is the difference between SOAP 1.1, SOAP 1.2, HTTP GET & HTTP POST methods for Android?

Differences in SOAP versions

Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.

The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.

The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.

In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.

SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.

There is not difine POST AND GET method for particular android....but all here is differance

GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.

What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.

POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.

Link to original IBM source

How do you access the value of an SQL count () query in a Java program

The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

rs3.getInt(1);

to get the value in the first, and in your case, only column.

How can I use Bash syntax in Makefile targets?

If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.

Undefined reference to static class member

With C++11, the above would be possible for basic types as

class Foo {
public:  
  static constexpr int MEMBER = 1;  
};

The constexpr part creates a static expression as opposed to a static variable - and that behaves just like an extremely simple inline method definition. The approach proved a bit wobbly with C-string constexprs inside template classes, though.

What is trunk, branch and tag in Subversion?

The trunk is the main line of development in a SVN repository.

A branch is a side-line of development created to make larger, experimental or disrupting work without annoying users of the trunk version. Also, branches can be used to create development lines for multiple versions of the same product, like having a place to backport bugfixes into a stable release.

Finally, tags are markers to highlight notable revisions in the history of the repository, usually things like "this was released as 1.0".

See the HTML version of "Version Control with Subversion", especially Chapter 4: Branching and Merging or buy it in paper (e.g. from amazon) for an in-depth discussion of the technical details.

As others (e.g. Peter Neubauer below) the underlying implementation as /tags /branches and /trunk directories is only conventional and not in any way enforced by the tools. Violating these conventions leads to confusion all around, as this breaks habits and expectations of others accessing the repository. Special care must be taken to avoid committing new changes into tags, which should be frozen.


I use TortoiseSVN but no Visual Studio integration. I keep the "Check for modifications" dialog open on the second monitor the whole time, so I can track which files I have touched. But see the "Best SVN Tools" question, for more recommendations.

How do I serialize a C# anonymous type to a JSON string?

public static class JsonSerializer
{
    public static string Serialize<T>(this T data)
    {
        try
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream();
            serializer.WriteObject(stream, data);
            string jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
            stream.Close();
            return jsonData;
        }
        catch
        {
            return "";
        }
    }
    public static T Deserialize<T>(this string jsonData)
    {
        try
        {
            DataContractJsonSerializer slzr = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
            T data = (T)slzr.ReadObject(stream);
            stream.Close();
            return data;
        }
        catch
        {
            return default(T);
        }
    }
}

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle savedInstanceState) you will get the Bundle null when activity get starts first time and it will get in use when activity orientation get changed .......

http://www.gitshah.com/2011/03/how-to-handle-screen-orientation_28.html

Android provides another elegant way of achieving this. To achieve this, we have to override a method called onSaveInstanceState(). Android platform allows the users to save any instance state. Instance state can be saved in the Bundle. Bundle is passed as argument to the onSaveInstanceState method.

we can load the saved instance state from the Bundle passed as argument to the onCreate method. We can also load the saved instance state in onRestoreInstanceState method. But I will leave that for the readers to figure out.

Angular ReactiveForms: Producing an array of checkbox values?

Make an event when it's clicked and then manually change the value of true to the name of what the check box represents, then the name or true will evaluate the same and you can get all the values instead of a list of true/false. Ex:

component.html

<form [formGroup]="customForm" (ngSubmit)="onSubmit()">
    <div class="form-group" *ngFor="let parameter of parameters"> <!--I iterate here to list all my checkboxes -->
        <label class="control-label" for="{{parameter.Title}}"> {{parameter.Title}} </label>
            <div class="checkbox">
              <input
                  type="checkbox"
                  id="{{parameter.Title}}"
                  formControlName="{{parameter.Title}}"
                  (change)="onCheckboxChange($event)"
                  > <!-- ^^THIS^^ is the important part -->
             </div>
      </div>
 </form>

component.ts

onCheckboxChange(event) {
    //We want to get back what the name of the checkbox represents, so I'm intercepting the event and
    //manually changing the value from true to the name of what is being checked.

    //check if the value is true first, if it is then change it to the name of the value
    //this way when it's set to false it will skip over this and make it false, thus unchecking
    //the box
    if(this.customForm.get(event.target.id).value) {
        this.customForm.patchValue({[event.target.id] : event.target.id}); //make sure to have the square brackets
    }
}

This catches the event after it was already changed to true or false by Angular Forms, if it's true I change the name to the name of what the checkbox represents, which if needed will also evaluate to true if it's being checked for true/false as well.

SystemError: Parent module '' not loaded, cannot perform relative import

I usually use this workaround:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.

Get string after character

Use parameter expansion, if the value is already stored in a variable.

$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}

Or use read

$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"

Either way,

$ echo $value
7.092200e-01

Measuring execution time of a function in C++

You can have a simple class which can be used for this kind of measurements.

class duration_printer {
public:
    duration_printer() : __start(std::chrono::high_resolution_clock::now()) {}
    ~duration_printer() {
        using namespace std::chrono;
        high_resolution_clock::time_point end = high_resolution_clock::now();
        duration<double> dur = duration_cast<duration<double>>(end - __start);
        std::cout << dur.count() << " seconds" << std::endl;
    }
private:
    std::chrono::high_resolution_clock::time_point __start;
};

The only thing is needed to do is to create an object in your function at the beginning of that function

void veryLongExecutingFunction() {
    duration_calculator dc;
    for(int i = 0; i < 100000; ++i) std::cout << "Hello world" << std::endl;
}

int main() {
    veryLongExecutingFunction();
    return 0;
}

and that's it. The class can be modified to fit your requirements.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

I encountered the same ImportError. Somehow the setuptools package had been deleted in my Python environment.

To fix the issue, run the setup script for setuptools:

curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python

If you have any version of distribute, or any setuptools below 0.6, you will have to uninstall it first.*

See Installation Instructions for further details.


* If you already have a working distribute, upgrading it to the "compatibility wrapper" that switches you over to setuptools is easier. But if things are already broken, don't try that.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

try

console.log($("#"+d));

your solution is passing the double quotes as part of the string.

Finding the source code for built-in Python functions?

As mentioned by @Jim, the file organization is described here. Reproduced for ease of discovery:

For Python modules, the typical layout is:

Lib/<module>.py
Modules/_<module>.c (if there’s also a C accelerator module)
Lib/test/test_<module>.py
Doc/library/<module>.rst

For extension-only modules, the typical layout is:

Modules/<module>module.c
Lib/test/test_<module>.py
Doc/library/<module>.rst

For builtin types, the typical layout is:

Objects/<builtin>object.c
Lib/test/test_<builtin>.py
Doc/library/stdtypes.rst

For builtin functions, the typical layout is:

Python/bltinmodule.c
Lib/test/test_builtin.py
Doc/library/functions.rst

Some exceptions:

builtin type int is at Objects/longobject.c
builtin type str is at Objects/unicodeobject.c
builtin module sys is at Python/sysmodule.c
builtin module marshal is at Python/marshal.c
Windows-only module winreg is at PC/winreg.c

mySQL :: insert into table, data from another table?

for whole row

insert into xyz select * from xyz2 where id="1";

for selected column

insert into xyz(t_id,v_id,f_name) select t_id,v_id,f_name from xyz2 where id="1";

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

How to load up CSS files using Javascript?

There is a general jquery plugin that loads css and JS files synch and asych on demand. It also keeps track off what is already been loaded :) see: http://code.google.com/p/rloader/

IndexOf function in T-SQL

CHARINDEX is what you are looking for

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

delete vs delete[] operators in C++

The operators delete and delete [] are used respectively to destroy the objects created with new and new[], returning to the allocated memory left available to the compiler's memory manager.

Objects created with new must necessarily be destroyed with delete, and that the arrays created with new[] should be deleted with delete[].

Drop a temporary table if it exists

From SQL Server 2016 you can just use

 DROP TABLE IF EXISTS ##CLIENTS_KEYWORD

On previous versions you can use

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
   client_id INT
)

You could also consider truncating the table instead rather than dropping and recreating.

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
  TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
  CREATE TABLE ##CLIENTS_KEYWORD
  (
     client_id INT
  ) 

How to set a time zone (or a Kind) of a DateTime value?

If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.

// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();

// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();

If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().

// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);

// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);

List of available timezones

TimeZoneInfo class on MSDN

Excel: Searching for multiple terms in a cell

In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH), using named ranges and the EVALUATE function as I found from this link.

For example, I put the following terms as text in a cell, $G$1:

"PRB", "utilization", "alignment", "spectrum"

Then, I defined a named range named search_terms for that cell as described in the link above and shown in the figure below:

Named range definition

In the Refers to: field I put the following:

=EVALUATE("{" & TDoc_List!$G$1 & "}")

The above EVALUATE expression is simple used to emulate the literal string

{"PRB", "utilization", "alignment", "spectrum"}

to be used as input to the SEARCH function: using a direct reference to the SINGLE cell $G$1 (augmented with the curly braces in that case) inside SEARCH does not work, hence the use of named ranges and EVALUATE.

The trick now consists in replacing the direct reference to $G$1 by the EVALUATE-augmented named range search_terms.

The formula

It really works, and shows once more how powerful Excel really is!

It really works!

Hope this helps.

How to drop a table if it exists?

In SQL Server 2016 (13.x) and above

DROP TABLE IF EXISTS dbo.Scores

In earlier versions

IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL 
DROP TABLE dbo.Scores; 

U is your table type

How to add include and lib paths to configure/make cycle?

Set LDFLAGS and CFLAGS when you run make:

$ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make

If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib

Android Layout Right Align

This is an example for a RelativeLayout:

RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                relativeLayout.setLayoutParams(params);

With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.

Apache error: _default_ virtualhost overlap on port 443

On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:

{apache_dir}/conf.d/ssl.conf

This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

ECMAScript 6 arrow function that returns an object

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

Google Spreadsheet, Count IF contains a string

Wildcards worked for me when the string I was searching for could be entered manually. However, I wanted to store this string in another cell and refer to it. I couldn't figure out how to do this with wildcards so I ended up doing the following:

A1 is the cell containing my search string. B and C are the columns within which I want to count the number of instances of A1, including within strings:

=COUNTIF(ARRAYFORMULA(ISNUMBER(SEARCH(A1, B:C))), TRUE)

Date / Timestamp to record when a record was added to the table?

You can make a default constraint on this column that will put a default getdate() as a value.

Example:

alter table dbo.TABLE 
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN

Is there an equivalent method to C's scanf in Java?

THERE'S an even simpler answer

import java.io.BufferedReader;
import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        String myBeautifulScanf = new Scanner(System.in).nextLine();
        System.out.println( myBeautifulScanf );

    }
}

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

This is an old thread, but another solution, which I prefer, is just update the cityId and not assign the hole model City to Employee... to do that Employee should look like:

public class Employee{
    ...
    public int? CityId; //The ? is for allow City nullable
    public virtual City City;
}

Then it's enough assigning:

e1.CityId=city1.ID;

How can I convert a DateTime to an int?

string date = DateTime.Now.ToString();

date = date.Replace("/", "");
date = date.Replace(":", "");
date = date.Replace(" ", "");
date = date.Replace("AM", "");
date = date.Replace("PM", "");            
return date;

No connection could be made because the target machine actively refused it?

I faced same error because when your Server and Client run on same machine the Client need server local ip address not Public ip address to communicate with server you need Public ip address only in case when Server and Client run on separate machine so use Local ip address in client program to connect with server Local ip address can be found using this method.

 public static string Getlocalip()
    {
        try
        {
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            return localIPs[7].ToString();
        }
        catch (Exception)
        {

            return "null";
        }

    }

How to get difference between two dates in Year/Month/Week/Day?

Days: (endDate - startDate).Days
Weeks: (endDate - startDate).Days / 7
Years: Months / 12
Months: A TimeSpan only provides Days, so use the following code to get the number of whole months between a specified start and end date. For example, the number of whole months between 01/10/2000 and 02/10/2000 is 1. The the number of whole months between 01/10/2000 and 02/09/2000 is 0.

    public int getMonths(DateTime startDate, DateTime endDate)
    {
        int months = 0;

        if (endDate.Month <= startDate.Month)
        {
            if (endDate.Day < startDate.Day)
            {
                months = (12 * (endDate.Year - startDate.Year - 1))
                       + (12 - startDate.Month + endDate.Month - 1);
            }
            else if (endDate.Month < startDate.Month)
            {
                months = (12 * (endDate.Year - startDate.Year - 1))
                       + (12 - startDate.Month + endDate.Month);
            }
            else  // (endDate.Month == startDate.Month) && (endDate.Day >= startDate.Day)
            {
                months = (12 * (endDate.Year - startDate.Year));
            }
        }
        else if (endDate.Day < startDate.Day)
        {
            months = (12 * (endDate.Year - startDate.Year))
                   + (endDate.Month - startDate.Month) - 1;
        }
        else  // (endDate.Month > startDate.Month) && (endDate.Day >= startDate.Day)
        {
            months = (12 * (endDate.Year - startDate.Year))
                   + (endDate.Month - startDate.Month);
        }

        return months;
    }

What is the App_Data folder used for in Visual Studio?

App_Data is essentially a storage point for file-based data stores (as opposed to a SQL server database store for example). Some simple sites make use of it for content stored as XML for example, typically where hosting charges for a DB are expensive.

How can I get a list of all classes within current module in Python?

Go to Python Interpreter. type help ('module_name') , then press Enter. e.g. help('os') . Here, I've pasted one part of the output below:

class statvfs_result(__builtin__.object)
     |  statvfs_result: Result from statvfs or fstatvfs.
     |
     |  This object may be accessed either as a tuple of
     |    (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),
     |  or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.
     |
     |  See os.statvfs for more information.
     |
     |  Methods defined here:
     |
     |  __add__(...)
     |      x.__add__(y) <==> x+y
     |
     |  __contains__(...)
     |      x.__contains__(y) <==> y in x

How to remove white space characters from a string in SQL Server

There may be 2 spaces after the text, please confirm. You can use LTRIM and RTRIM functions also right?

LTRIM(RTRIM(ProductAlternateKey))

Maybe the extra space isn't ordinary spaces (ASCII 32, soft space)? Maybe they are "hard space", ASCII 160?

ltrim(rtrim(replace(ProductAlternateKey, char(160), char(32))))

Push items into mongo array via mongoose

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

Update the model in-memory, and save (plain javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

How to determine SSL cert expiration date from a PEM encoded certificate?

If you just want to know whether the certificate has expired (or will do so within the next N seconds), the -checkend <seconds> option to openssl x509 will tell you:

if openssl x509 -checkend 86400 -noout -in file.pem
then
  echo "Certificate is good for another day!"
else
  echo "Certificate has expired or will do so within 24 hours!"
  echo "(or is invalid/not found)"
fi

This saves having to do date/time comparisons yourself.

openssl will return an exit code of 0 (zero) if the certificate has not expired and will not do so for the next 86400 seconds, in the example above. If the certificate will have expired or has already done so - or some other error like an invalid/nonexistent file - the return code is 1.

(Of course, it assumes the time/date is set correctly)

Be aware that older versions of openssl have a bug which means if the time specified in checkend is too large, 0 will always be returned (https://github.com/openssl/openssl/issues/6180).

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

And yet another option: https://github.com/apptik/jus

  • It is modular like Volley, but more extended and documentation is improving, supporting different HTTP stacks and converters out of the box
  • It has a module to generate server API interface mappings like Retrofit
  • It also has JavaRx support

And many other handy features like markers, transformers, etc.

iOS 7 UIBarButton back button arrow color

To change the back button chevron color for a specific navigation controller*:

self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

*If you are using an app with more than 1 navigation controller, and you want this chevron color to apply to each, you may want to use the appearance proxy to set the back button chevron for every navigation controller, as follows:

[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

And for good measure, in swift (thanks to Jay Mayu in the comments):

UINavigationBar.appearance().tintColor = UIColor.whiteColor()

How enable auto-format code for Intellij IDEA?

In Mac it is Alt+Command+L(assuming you haven't changed any of your modifier keys or Intellij keyboard shortcuts from it's default state)

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
 //do stuff
}

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

Edit:
In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

Flattening a shallow list in Python

In Python 2.6, using chain.from_iterable():

>>> from itertools import chain
>>> list(chain.from_iterable(mi.image_set.all() for mi in h.get_image_menu()))

It avoids creating of intermediate list.

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

How to activate "Share" button in android app?

Create a button with an id share and add the following code snippet.

share.setOnClickListener(new View.OnClickListener() {             
    @Override
    public void onClick(View v) {

        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = "Your body here";
        String shareSub = "Your subject here";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
    }
});

The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

How to write inline if statement for print?

Well why don't you simply write:

if b:
    print a
else:
    print 'b is false'

Laravel Eloquent groupBy() AND also return count of each group

This is working for me:

$user_info = DB::table('usermetas')
                 ->select('browser', DB::raw('count(*) as total'))
                 ->groupBy('browser')
                 ->get();

Is there a way to specify a default property value in Spring XML?

The default value can be followed with a : after the property key, e.g.

<property name="port" value="${my.server.port:8080}" />

Or in java code:

@Value("${my.server.port:8080}")
private String myServerPort;

See:

BTW, the Elvis Operator is only available within Spring Expression Language (SpEL),
e.g.: https://stackoverflow.com/a/37706167/537554

Measure string size in Bytes in php

You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:

<?php
    $string = 'Cién cañones por banda';
    echo mb_strlen($string, '8bit');
?>

You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php

For trim the string by byte length without split in middle of a multibyte character you can use:

mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )

IOS - How to segue programmatically using swift

You can do this thing using performSegueWithIdentifier function.

Screenshot

Syntax :

func performSegueWithIdentifier(identifier: String, sender: AnyObject?)

Example :

 performSegueWithIdentifier("homeScreenVC", sender: nil)

How can I import Swift code to Objective-C?

If you want to use Swift file into Objective-C class, so from Xcode 8 onwards you can follow below steps:

If you have created the project in Objective-C:

  1. Create new Swift file
  2. Xcode will automatically prompt for Bridge-Header file
  3. Generate it
  4. Import "ProjectName-Swift.h" in your Objective-C controller (import in implementation not in interface) (if your project has space in between name so use underscore "Project_Name-Swift.h")
  5. You will be able to access your Objective-C class in Swift.

Compile it and if it will generate linker error like: compiled with newer version of Swift language (3.0) than previous files (2.0) for architecture x86_64 or armv 7

Make one more change in your

  1. Xcode -> Project -> Target -> Build Settings -> Use Legacy Swift Language Version -> Yes

Build and Run.

What does elementFormDefault do in XSD?

Consider the following ComplexType AuthorType used by author element

<xsd:complexType name="AuthorType">
  <!-- compositor goes here -->
  <xsd:sequence>
     <xsd:element name="name" type="xsd:string"/>
     <xsd:element name="phone" type="tns:Phone"/>
  </xsd:sequence>
  <xsd:attribute name="id" type="tns:AuthorId"/>
</xsd:complexType>
<xsd:element name="author" type="tns:AuthorType"/>

If elementFormDefault="unqualified"

then following XML Instance is valid

<x:author xmlns:x="http://example.org/publishing">
   <name>Aaron Skonnard</name>
   <phone>(801)390-4552</phone>
</x:author>

the authors's name attribute is allowed without specifying the namespace(unqualified). Any elements which are a part of <xsd:complexType> are considered as local to complexType.

if elementFormDefault="qualified"

then the instance should have the local elements qualified

<x:author xmlns:x="http://example.org/publishing">
   <x:name>Aaron Skonnard</name>
   <x:phone>(801)390-4552</phone>
</x:author>

please refer this link for more details

How to use support FileProvider for sharing content to other apps?

Fully working code sample how to share file from inner app folder. Tested on Android 7 and Android 5.

AndroidManifest.xml

</application>
   ....
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="android.getqardio.com.gmslocationtest"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

xml/provider_paths

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path
        name="share"
        path="external_files"/>
</paths>

Code itself

    File imagePath = new File(getFilesDir(), "external_files");
    imagePath.mkdir();
    File imageFile = new File(imagePath.getPath(), "test.jpg");

    // Write data in your file

    Uri uri = FileProvider.getUriForFile(this, getPackageName(), imageFile);

    Intent intent = ShareCompat.IntentBuilder.from(this)
                .setStream(uri) // uri from FileProvider
                .setType("text/html")
                .getIntent()
                .setAction(Intent.ACTION_VIEW) //Change if needed
                .setDataAndType(uri, "image/*")
                .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

   startActivity(intent);

SQLAlchemy equivalent to SQL "LIKE" statement

If you use native sql, you can refer to my code, otherwise just ignore my answer.

SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text

bar_tags = "banana"

# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""

# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()

how to remove "," from a string in javascript

<script type="text/javascript">var s = '/Controller/Action#11112';if(typeof s == 'string' && /\?*/.test(s)){s = s.replace(/\#.*/gi,'');}document.write(s);</script>

It's more common answer. And can be use with s= document.location.href;

Plotting a list of (x, y) coordinates in python matplotlib

As per this example:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

will produce:

enter image description here

To unpack your data from pairs into lists use zip:

x, y = zip(*li)

So, the one-liner:

plt.scatter(*zip(*li))

Access VBA | How to replace parts of a string with another string

Since the string "North" might be the beginning of a street name, e.g. "Northern Boulevard", street directions are always between the street number and the street name, and separated from street number and street name.

Public Function strReplace(varValue As Variant) as Variant

Select Case varValue

    Case "Avenue"
        strReplace = "Ave"

    Case " North "
        strReplace = " N "

    Case Else
        strReplace = varValue

End Select

End Function

Android selector & text color

Have you tried setOnFocusChangeListener? Within the handler, you could change the text appearance.

For instance:

TextView text = (TextView)findViewById(R.id.text);
text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            ((TextView)v).setXXXX();
        } else {
            ((TextView)v).setXXXX();
        }
    }
});

You can then apply whatever changes you want when it's focused or not. You can also use the ViewTreeObserver to listen for Global focus changes.

For instance:

View all = findViewById(R.id.id_of_top_level_view_on_layout);
ViewTreeObserver vto = all.getViewTreeObserver();
vto.addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
    public void onGlobalFocusChanged(
        View oldFocus, View newFocus) {
        // xxxx
    }
});

I hope this helps or gives you ideas.

How can I get LINQ to return the object which has the max value for a given property?

In case you don't want to use MoreLINQ and want to get linear time, you can also use Aggregate:

var maxItem = 
  items.Aggregate(
    new { Max = Int32.MinValue, Item = (Item)null },
    (state, el) => (el.ID > state.Max) 
      ? new { Max = el.ID, Item = el } : state).Item;

This remembers the current maximal element (Item) and the current maximal value (Item) in an anonymous type. Then you just pick the Item property. This is indeed a bit ugly and you could wrap it into MaxBy extension method to get the same thing as with MoreLINQ:

public static T MaxBy(this IEnumerable<T> items, Func<T, int> f) {
  return items.Aggregate(
    new { Max = Int32.MinValue, Item = default(T) },
    (state, el) => {
      var current = f(el.ID);
      if (current > state.Max) 
        return new { Max = current, Item = el };
      else 
        return state; 
    }).Item;
}

Change the location of the ~ directory in a Windows install of Git Bash

So, $HOME is what I need to modify. However I have been unable to find where this mythical $HOME variable is set so I assumed it was a Linux system version of PATH or something. Anyway...**

Answer

Adding HOME at the top of the profile file worked.

HOME="c://path/to/custom/root/".

  #THE FIX WAS ADDING THE FOLLOWING LINE TO THE TOP OF THE PROFILE FILE

  HOME="c://path/to/custom/root/"

  # below are the original contents ===========
  # To the extent possible under law, ..blah blah

  # Some resources...
  # Customizing Your Shell: http://www.dsl.org/cookbook/cookbook_5.html#SEC69
  # Consistent BackSpace and Delete Configuration:
  #   http://www.ibb.net/~anne/keyboard.html
  # The Linux Documentation Project: http://www.tldp.org/
  # The Linux Cookbook: http://www.tldp.org/LDP/linuxcookbook/html/
  # Greg's Wiki http://mywiki.wooledge.org/

  # Setup some default paths. Note that this order will allow user installed
  # software to override 'system' software.
  # Modifying these default path settings can be done in different ways.
  # To learn more about startup files, refer to your shell's man page.

  MSYS2_PATH="/usr/local/bin:/usr/bin:/bin"
  MANPATH="/usr/local/man:/usr/share/man:/usr/man:/share/man:${MANPATH}"
  INFOPATH="/usr/local/info:/usr/share/info:/usr/info:/share/info:${INFOPATH}"
  MINGW_MOUNT_POINT=
  if [ -n "$MSYSTEM" ]
  then
    case "$MSYSTEM" in
      MINGW32)
        MINGW_MOUNT_POINT=/mingw32
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MINGW64)
        MINGW_MOUNT_POINT=/mingw64
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MSYS)
        PATH="${MSYS2_PATH}:/opt/bin:${PATH}"
        PKG_CONFIG_PATH="/usr/lib/pkgconfig:/usr/share/pkgconfig:/lib/pkgconfig"
      ;;
      *)
        PATH="${MSYS2_PATH}:${PATH}"
      ;;
    esac
  else
    PATH="${MSYS2_PATH}:${PATH}"
  fi

  MAYBE_FIRST_START=false
  SYSCONFDIR="${SYSCONFDIR:=/etc}"

  # TMP and TEMP as defined in the Windows environment must be kept
  # for windows apps, even if started from msys2. However, leaving
  # them set to the default Windows temporary directory or unset
  # can have unexpected consequences for msys2 apps, so we define
  # our own to match GNU/Linux behaviour.
  ORIGINAL_TMP=$TMP
  ORIGINAL_TEMP=$TEMP
  #unset TMP TEMP
  #tmp=$(cygpath -w "$ORIGINAL_TMP" 2> /dev/null)
  #temp=$(cygpath -w "$ORIGINAL_TEMP" 2> /dev/null)
  #TMP="/tmp"
  #TEMP="/tmp"
  case "$TMP" in *\\*) TMP="$(cygpath -m "$TMP")";; esac
  case "$TEMP" in *\\*) TEMP="$(cygpath -m "$TEMP")";; esac
  test -d "$TMPDIR" || test ! -d "$TMP" || {
    TMPDIR="$TMP"
    export TMPDIR
  }


  # Define default printer
  p='/proc/registry/HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/Windows/Device'
  if [ -e "${p}" ] ; then
    read -r PRINTER < "${p}"
    PRINTER=${PRINTER%%,*}
  fi
  unset p

  print_flags ()
  {
    (( $1 & 0x0002 )) && echo -n "binary" || echo -n "text"
    (( $1 & 0x0010 )) && echo -n ",exec"
    (( $1 & 0x0040 )) && echo -n ",cygexec"
    (( $1 & 0x0100 )) && echo -n ",notexec"
  }

  # Shell dependent settings
  profile_d ()
  {
    local file=
    for file in $(export LC_COLLATE=C; echo /etc/profile.d/*.$1); do
      [ -e "${file}" ] && . "${file}"
    done

    if [ -n ${MINGW_MOUNT_POINT} ]; then
      for file in $(export LC_COLLATE=C; echo ${MINGW_MOUNT_POINT}/etc/profile.d/*.$1); do
        [ -e "${file}" ] && . "${file}"
      done
    fi
  }

  for postinst in $(export LC_COLLATE=C; echo /etc/post-install/*.post); do
    [ -e "${postinst}" ] && . "${postinst}"
  done

  if [ ! "x${BASH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    [ -f "/etc/bash.bashrc" ] && . "/etc/bash.bashrc"
  elif [ ! "x${KSH_VERSION}" = "x" ]; then
    typeset -l HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1=$(print '\033]0;${PWD}\n\033[32m${USER}@${HOSTNAME} \033[33m${PWD/${HOME}/~}\033[0m\n$ ')
  elif [ ! "x${ZSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d zsh
    PS1='(%n@%m)[%h] %~ %% '
  elif [ ! "x${POSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    PS1="$ "
  else
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1="$ "
  fi

  if [ -n "$ACLOCAL_PATH" ]
  then
    export ACLOCAL_PATH
  fi

  export PATH MANPATH INFOPATH PKG_CONFIG_PATH USER TMP TEMP PRINTER HOSTNAME PS1 SHELL tmp temp
  test -n "$TERM" || export TERM=xterm-256color

  if [ "$MAYBE_FIRST_START" = "true" ]; then
    sh /usr/bin/regen-info.sh

    if [ -f "/usr/bin/update-ca-trust" ]
    then
      sh /usr/bin/update-ca-trust
    fi

    clear
    echo
    echo
    echo "###################################################################"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "#                   C   A   U   T   I   O   N                     #"
    echo "#                                                                 #"
    echo "#                  This is first start of MSYS2.                  #"
    echo "#       You MUST restart shell to apply necessary actions.        #"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "###################################################################"
    echo
    echo
  fi
  unset MAYBE_FIRST_START

GROUP BY with MAX(DATE)

You cannot include non-aggregated columns in your result set which are not grouped. If a train has only one destination, then just add the destination column to your group by clause, otherwise you need to rethink your query.

Try:

SELECT t.Train, t.Dest, r.MaxTime
FROM (
      SELECT Train, MAX(Time) as MaxTime
      FROM TrainTable
      GROUP BY Train
) r
INNER JOIN TrainTable t
ON t.Train = r.Train AND t.Time = r.MaxTime

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

function Time_Function() {
var date = new Date()
var time =""
var x= "AM"
if(date.getHours() >12){
    x= "PM"
}
time= date.getHours()%12 + x +":"+ date.getMinutes() +":"+ date.getSeconds()
}

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

Is there an API to get bank transaction and bank balance?

I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.

Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.

In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.

This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.

OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory

Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Either you experienced database connection issue or you missed any of the hibernate configurations to connect to database such as database DIALECT.

Happens if your database server was disconnected due to network related issue.

If you're using spring boot along with hibernate connected to Oracle Db, use

hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true
entitymanager.packagesToScan: com

How to add Tomcat Server in eclipse

Most of the time when we download tomcat and extract the file a folder will be created:

C:\Program Files\apache-tomcat-9.0.1-windows-x64

Inside that actual tomcat folder will be there:

C:\Program Files\apache-tomcat-9.0.1-windows-x64\apache-tomcat-9.0.1

so while selecting you need to select inner folder:

C:\Program Files\apache-tomcat-9.0.1-windows-x64\apache-tomcat-9.0.1

instead of the outer.

Select default option value from typescript angular 6

For reactive form, I managed to make it work by using the following example (47 can be replaced with other value or variable):

<div [formGroup]="form">
  <select formControlName="fieldName">
    <option
        *ngFor="let option of options; index as i"
        [selected]="option === 47"
    >
        {{ option }}
    </option>
  </select>
</div>

What is polymorphism, what is it for, and how is it used?

Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction and a class called ComplexNumber, both of these might include a method called display(), but each of them would implement that method differently. In PHP, for example, you might implement it like this:

//  Class definitions

class Fraction
{
    public $numerator;
    public $denominator;

    public function __construct($n, $d)
    {
        //  In real life, you'd do some type checking, making sure $d != 0, etc.
        $this->numerator = $n;
        $this->denominator = $d;
    }

    public function display()
    {
        echo $this->numerator . '/' . $this->denominator;
    }
}

class ComplexNumber
{
    public $real;
    public $imaginary;

    public function __construct($a, $b)
    {
        $this->real = $a;
        $this->imaginary = $b;
    }

    public function display()
    {
        echo $this->real . '+' . $this->imaginary . 'i';
    }
}


//  Main program

$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);

echo 'This is a fraction: '
$fraction->display();
echo "\n";

echo 'This is a complex number: '
$complex->display();
echo "\n";

Outputs:

This is a fraction: 1/2
This is a complex number: 1 + 2i

Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction and ComplexNumber both implement an abstract class called Number that has a method display(), which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.

At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number created:

$userNumberChoice = $_GET['userNumberChoice'];

switch ($userNumberChoice) {
    case 'fraction':
        $userNumber = new Fraction(1, 2);
        break;
    case 'complex':
        $userNumber = new ComplexNumber(1, 2);
        break;
}

echo "The user's number is: ";
$userNumber->display();
echo "\n";

In this case, the appropriate display() method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.

failed to push some refs to [email protected]

It would appear that you are not fully up-to-date. You would need to do a git pull and either "--rebase" or let it merge into your set.

After this, you should then be able to push, since it would be a 'fast-forward' change that wouldn't remove history.

Edit: example command list

git pull
git push

Create a new TextView programmatically then display it below another TextView

If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.

Complete code:

String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);        
for( int i = 0; i < textArray.length; i++ )
{
    TextView textView = new TextView(this);
    textView.setText(textArray[i]);
    linearLayout.addView(textView);
}

Android: Reverse geocoding - getFromLocation

Use this

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

Detecting Browser Autofill

I know this is an old thread but I can imagine many comes to find a solution to this here.

To do this, you can check if the input(s) has value(s) with:

$(function() {
    setTimeout(function() {
        if ($("#inputID").val().length > 0) {
            // YOUR CODE
        }
    }, 100);
});

I use this myself to check for values in my login form when it's loaded to enable the submit button. The code is made for jQuery but is easy to change if needed.

MySQL Error 1264: out of range value for column

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

ALTER TABLE T_PERSON MODIFY mobile_no BIGINT;

How can I use mySQL replace() to replace strings in multiple records?

Check this

UPDATE some_table SET some_field = REPLACE("Column Name/String", 'Search String', 'Replace String')

Eg with sample string:

UPDATE some_table SET some_field = REPLACE("this is test string", 'test', 'sample')

EG with Column/Field Name:

UPDATE some_table SET some_field = REPLACE(columnName, 'test', 'sample')

Python Sets vs Lists

Set wins due to near instant 'contains' checks: https://en.wikipedia.org/wiki/Hash_table

List implementation: usually an array, low level close to the metal good for iteration and random access by element index.

Set implementation: https://en.wikipedia.org/wiki/Hash_table, it does not iterate on a list, but finds the element by computing a hash from the key, so it depends on the nature of the key elements and the hash function. Similar to what is used for dict. I suspect list could be faster if you have very few elements (< 5), the larger element count the better the set will perform for a contains check. It is also fast for element addition and removal. Also always keep in mind that building a set has a cost !

NOTE: If the list is already sorted, searching the list could be quite fast on small lists, but with more data a set is faster for contains checks.

How to get the browser language using JavaScript

The "JavaScript" way:

var lang = navigator.language || navigator.userLanguage; //no ?s necessary

Really you should be doing language detection on the server, but if it's absolutely necessary to know/use via JavaScript, it can be gotten.

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

I've done some workaround utility function, using imagesLoaded jquery plugin: https://github.com/desandro/imagesloaded

            function waitForImageSize(src, func, ctx){
                if(!ctx)ctx = window;
                var img = new Image();
                img.src = src;
                $(img).imagesLoaded($.proxy(function(){
                    var w = this.img.innerWidth||this.img.naturalWidth;
                    var h = this.img.innerHeight||this.img.naturalHeight;
                    this.func.call(this.ctx, w, h, this.img);
                },{img: img, func: func, ctx: ctx}));
            },

You can use this by passing url, function and its context. Function is performed after image is loaded and return created image, its width and height.

waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)

error: expected declaration or statement at end of input in c

Try to place a

return 0;

on the end of your code or just erase the

void

from your main function I hope that I helped

How to diff one file to an arbitrary version in Git?

If you are fine using a graphical tool (or even prefer it) you can:

gitk pom.xml

In gitk you can then click any commit (to "select" it) and right click any other commit to select "Diff this -> selected" or "Diff selected -> this" in the popup menu, depending on what order you prefer.

How to compare two java objects

You need to implement the equals() method in your MyClass.

The reason that == didn't work is this is checking that they refer to the same instance. Since you did new for each, each one is a different instance.

The reason that equals() didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==.

Note that you should also implement hashcode() if you're going to implement equals() because a lot of java.util Collections expect that.

PHP Pass variable to next page

There are three method to pass value in php.

  • By post
  • By get
  • By making session variable

These three method are used for different purpose.For example if we want to receive our value on next page then we can use 'post' ($_POST) method as:-

$a=$_POST['field-name'];

If we require the value of variable on more than one page than we can use session variable as:-

$a=$_SESSION['field-name];

Before using this Syntax for creating SESSION variable we first have to add this tag at the very beginning of our php page

session_start(); 

GET method are generally used to print data on same page which used to take input from user. Its syntax is as:

$a=$_GET['field-name'];

POST method are generally consume more secure than GET because when we use Get method than it can display the data in URL bar.If the data is more sensitive data like password then it can be inggeris.

How to set NODE_ENV to production/development in OS X

npm start --mode production
npm start --mode development

With process.env.NODE_ENV = 'production'

How to compare types

If your instance is a Type:

Type typeFiled;
if (typeField == typeof(string))
{ 
    ... 
}

but if your instance is an object and not a Type use the as operator:

object value;
string text = value as string;
if (text != null)
{
    // value is a string and you can do your work here
}

this has the advantage to convert value only once into the specified type.

Same font except its weight seems different on different browsers

I collected and tested discussed solutions:

Windows10 Prof x64:

* FireFox v.56.0 x32 
* Opera v.49.0
* Google Chrome v.61.0.3163.100 x64-bit

macOs X Serra v.10.12.6 Mac mini (Mid 2010):

* Safari v.10.1.2(12603.3.8)
* FireFox v.57.0 Quantum
* Opera v49.0

Semi (still micro fat in Safari) solved fatty fonts:

text-transform: none; // mac ff fix
-webkit-font-smoothing: antialiased; // safari mac nicer
-moz-osx-font-smoothing: grayscale; // fix fatty ff on mac

Have no visual effect

line-height: 1;
text-rendering: optimizeLegibility; 
speak: none;
font-style: normal;
font-variant: normal;

Wrong visual effect:

-webkit-font-smoothing: subpixel-antialiased !important; //more fatty in safari
text-rendering: geometricPrecision !important; //more fatty in safari

do not forget to set !important when testing or be sure that your style is not overridden

copying all contents of folder to another folder using batch file?

xcopy.exe is the solution here. It's built into Windows.

xcopy /s c:\Folder1 d:\Folder2

You can find more options at http://www.computerhope.com/xcopyhlp.htm

How can I create objects while adding them into a vector?

I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

#include <iostream>
#include <vector>

class Box
{
    public:

    static int BoxesTotal;
    static int BoxesEver;
    int Id;

    Box()
    {
        ++BoxesTotal;
        ++BoxesEver;
        Id = BoxesEver;
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
    }

    ~Box()
    {
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
        --BoxesTotal;
    }

};

int Box::BoxesTotal = 0;
int Box::BoxesEver = 0;

int main(int argc, char* argv[])
{
    std::cout << "Objects (Boxes) example." << std::endl;
    std::cout << "------------------------" << std::endl;

    std::vector <Box*> BoxesTab;

    Box* Indicator;
    for (int i = 1; i<4; ++i)
    {
        std::cout << "i = " << i << ":" << std::endl;
        Box* Indicator = new(Box);
        BoxesTab.push_back(Indicator);
        std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
    }

    std::cout << "Summary" << std::endl;
    std::cout << "-------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
    }

    std::cout << "Deleting" << std::endl;
    std::cout << "--------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
        Indicator = (BoxesTab[i]);
        delete(Indicator);
    }

    return 0;
}

And the result it produces is:

Objects (Boxes) example.
------------------------
i = 1:
Box (1/1/1) initialized.
Adres Blowera: 0xdf8ca0
i = 2:
Box (2/2/2) initialized.
Adres Blowera: 0xdf8ce0
i = 3:
Box (3/3/3) initialized.
Adres Blowera: 0xdf8cc0
Summary
-------
Adres Blowera: 0xdf8ca0
Adres Blowera: 0xdf8ce0
Adres Blowera: 0xdf8cc0
Deleting
--------
Deleting Box: 1 (0xdf8ca0) 
Box (1/3/3) ended.
Deleting Box: 2 (0xdf8ce0) 
Box (2/2/3) ended.
Deleting Box: 3 (0xdf8cc0) 
Box (3/1/3) ended.

Why does cURL return error "(23) Failed writing body"?

I had the same error but from different reason. In my case I had (tmpfs) partition with only 1GB space and I was downloading big file which finally filled all memory on that partition and I got the same error as you.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

How to use sessions in an ASP.NET MVC 4 application?

Try

//adding data to session
//assuming the method below will return list of Products

var products=Db.GetProducts();

//Store the products to a session

Session["products"]=products;

//To get what you have stored to a session

var products=Session["products"] as List<Product>;

//to clear the session value

Session["products"]=null;

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Python POST binary data

you need to add Content-Disposition header, smth like this (although I used mod-python here, but principle should be the same):

request.headers_out['Content-Disposition'] = 'attachment; filename=%s' % myfname

How can I count the numbers of rows that a MySQL query returned?

Assuming you're using the mysql_ or mysqli_ functions, your question should already have been answered by others.

However if you're using PDO, there is no easy function to return the number of rows retrieved by a select statement, unfortunately. You have to use count() on the resultset (after assigning it to a local variable, usually).

Or if you're only interested in the number and not the data, PDOStatement::fetchColumn() on your SELECT COUNT(1)... result.

How to set-up a favicon?

In my site, I use this:

<!-- for FF, Chrome, Opera -->
<link rel="icon" type="image/png" href="/assets/favicons/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/assets/favicons/favicon-32x32.png" sizes="32x32">

<!-- for IE -->
<link rel="icon" type="image/x-icon" href="/assets/favicons/favicon.ico" >
<link rel="shortcut icon" type="image/x-icon" href="/assets/favicons/favicon.ico"/>

To simplify your life, use this favicons generator http://realfavicongenerator.net

Java HashMap: How to get a key and value by index?

HashMaps are not ordered, unless you use a LinkedHashMap or SortedMap. In this case, you may want a LinkedHashMap. This will iterate in order of insertion (or in order of last access if you prefer). In this case, it would be

int index = 0;
for ( Map.Entry<String,ArrayList<String>> e : myHashMap.iterator().entrySet() ) {
    String key = e.getKey();
    ArrayList<String> val = e.getValue();
    index++;
}

There is no direct get(index) in a map because it is an unordered list of key/value pairs. LinkedHashMap is a special case that keeps the order.

Simplest way to merge ES6 Maps/Sets?

The approved answer is great but that creates a new set every time.

If you want to mutate an existing object instead, use a helper function.

Set

function concatSets(set, ...iterables) {
    for (const iterable of iterables) {
        for (const item of iterable) {
            set.add(item);
        }
    }
}

Usage:

const setA = new Set([1, 2, 3]);
const setB = new Set([4, 5, 6]);
const setC = new Set([7, 8, 9]);
concatSets(setA, setB, setC);
// setA will have items 1, 2, 3, 4, 5, 6, 7, 8, 9

Map

function concatMaps(map, ...iterables) {
    for (const iterable of iterables) {
        for (const item of iterable) {
            map.set(...item);
        }
    }
}

Usage:

const mapA = new Map().set('S', 1).set('P', 2);
const mapB = new Map().set('Q', 3).set('R', 4);
concatMaps(mapA, mapB);
// mapA will have items ['S', 1], ['P', 2], ['Q', 3], ['R', 4]

How do I overload the [] operator in C#

public int this[int index]
{
    get => values[index];
}