Programs & Examples On #Eps

EPS is the common abbreviation for Encapsulated PostScript, a restricted version of PostScript meant to be embedded within other documents.

Error including image in Latex

I had the same problem, caused by a clash between the graphicx package and an inclusion of the epsfig package that survived the ages...

Please check that there is no inclusion of epsfig, it is deprecated.

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

AngularJS: How do I manually set input to $valid in controller?

I came across this post w/a similar issue. My fix was to add a hidden field to hold my invalid state for me.

<input type="hidden" ng-model="vm.application.isValid" required="" />

In my case I had a nullable bool which a person had to select one of two different buttons. if they answer yes, an entity is added to the collection and the state of the button changes. Until all of the questions get answered, (one of the buttons in each of the pairs has a click) the form is not valid.

vm.hasHighSchool = function (attended) { 
  vm.application.hasHighSchool = attended;
  applicationSvc.addSchool(attended, 1, vm.application);
}
<input type="hidden" ng-model="vm.application.hasHighSchool" required="" />
<div class="row">
  <div class="col-lg-3"><label>Did You Attend High School?</label><label class="required" ng-hide="vm.application.hasHighSchool != undefined">*</label></div>
  <div class="col-lg-2">
    <button value="Yes" title="Yes" ng-click="vm.hasHighSchool(true)" class="btn btn-default" ng-class="{'btn-success': vm.application.hasHighSchool == true}">Yes</button>
    <button value="No" title="No" ng-click="vm.hasHighSchool(false)" class="btn btn-default" ng-class="{'btn-success':  vm.application.hasHighSchool == false}">No</button>
  </div>
</div>

How to change the height of a <br>?

Instead of

<br>,<br/>,<hr> or <span></span> and trying different CSS properties to these tag.

I did, I put paragraphs inside a div and gave it line-height:2px

#html

<div class="smallerlineHeight">
   <p>Line1</p>
   <p>Line2</p>
</div>

#css

.smallerlineHeight {
    p {
        line-height: 2px;
    }
}

How is TeamViewer so fast?

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

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

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

Javascript change color of text and background to input value

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

HTML:

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

JS:

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

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

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

This Handler class should be static or leaks might occur: IncomingHandler

I am not sure but you can try intialising handler to null in onDestroy()

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
              from names) n2
  on (n2.author_id = n1.author_id)
Where true

used distinct if more inner join, because more join group performance is slow

MessageBodyWriter not found for media type=application/json

Uncommenting the below code helped

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
</dependency>

which was present in pom.xml in my maven based project resolved this error for me.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had the same problem, and my solving was to replace :

return redirect(url_for('index'))

with

return render_template('indexo.html',data=Todos.query.all())

in my POST and DELETE route.

Different CURRENT_TIMESTAMP and SYSDATE in oracle

CURRENT_DATE and CURRENT_TIMESTAMP return the current date and time in the session time zone.

SYSDATE and SYSTIMESTAMP return the system date and time - that is, of the system on which the database resides.

If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS* and CURRENT_* functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.

You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.

Service located in another namespace

I stumbled over the same issue and found a nice solution which does not need any static ip configuration:

You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local

You can use that DNS name to reference it in another namespace via a local service:

kind: Service
apiVersion: v1
metadata:
  name: service-y
  namespace: namespace-a
spec:
  type: ExternalName
  externalName: service-x.namespace-b.svc.cluster.local
  ports:
  - port: 80

Google Map API - Removing Markers

You can try this

    markers[markers.length-1].setMap(null);

Hope it works.

How to get http headers in flask?

Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.

enter image description here

The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

After params, let's now see how to get the headers:

enter image description here

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

Now let's see how to get the body

enter image description here

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

so we fetch the uploaded files with request.files and text with request.form

Exit while loop by user hitting ENTER key

if repr(User) == repr(''):
    break

Setting the default page for ASP.NET (Visual Studio) server configuration

If you are running against IIS rather than the VS webdev server, ensure that Index.aspx is one of your default files and that directory browsing is turned off.

Eclipse error: 'Failed to create the Java Virtual Machine'

1. Open the eclipse.ini file from your eclipse folder,see the picture below.

eclipse.ini

2. Open eclipse.ini in Notepad or any other text-editor application, Find the line -Xmx256m (or -Xmx1024m). Now change the default value 256m (or 1024m) to 512m. You also need to give the exact java installed version (1.6 or 1.7 or other).

max size

Like This:

-Xmx512m
-Dosgi.requiredJavaVersion=1.6

OR

-Xmx512m
-Dosgi.requiredJavaVersion=1.7

OR

-Xmx512m
-Dosgi.requiredJavaVersion=1.8

Then it works well for me.

How can I define colors as variables in CSS?

People keep upvoting my answer, but it's a terrible solution compared to the joy of sass or less, particularly given the number of easy to use gui's for both these days. If you have any sense ignore everything I suggest below.

You could put a comment in the css before each colour in order to serve as a sort of variable, which you can change the value of using find/replace, so...

At the top of the css file

/********************* Colour reference chart****************
*************************** comment ********* colour ******** 

box background colour       bbg              #567890
box border colour           bb               #abcdef
box text colour             bt               #123456

*/

Later in the CSS file

.contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456}

Then to, for example, change the colour scheme for the box text you do a find/replace on

/*bt*/#123456

How do I give text or an image a transparent background using CSS?

In Firefox 3 and Safari 3, you can use RGBA like Georg Schölly mentioned.

A little known trick is that you can use it in Internet Explorer as well using the gradient filter.

background-color: rgba(0, 255, 0, 0.5);
filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#7F00FF00', EndColorStr='#7F00FF00');

The first hex number defines the alpha value of the color.

Full solution all browsers:

.alpha60 {
    /* Fallback for web browsers that doesn't support RGBa */
    background: rgb(0, 0, 0) transparent;
    /* RGBa with 0.6 opacity */
    background: rgba(0, 0, 0, 0.6);
    /* For IE 5.5 - 7*/
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}

This is from CSS background transparency without affecting child elements, through RGBa and filters.

Screenshots proof of results:

This is when using the following code:

 <head>
     <meta http-equiv="X-UA-Compatible" content="IE=edge" >
    <title>An XHTML 1.0 Strict standard template</title>
     <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <style type="text/css" media="all">
         .transparent-background-with-text-and-images-on-top {
             background: rgb(0, 0, 0) transparent;   /* Fallback for web browsers that doesn't support RGBa */
            background: rgba(0, 0, 0, 0.6);   /* RGBa with 0.6 opacity */
             filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);  /* For IE 5.5 - 7*/
            -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";  /* For IE 8*/
         }
     </style>
 </head>

 <body>
     <div class="transparent-background-with-text-and-images-on-top">
         <p>Here some content (text AND images) "on top of the transparent background"</p>
        <img src="http://i.imgur.com/LnnghmF.gif">
     </div>
 </body>
 </html>

Chrome-33 IE11 IE9 IE8

How can I use jQuery in Greasemonkey?

You might get Component unavailable if you import the jQuery script directly.

Maybe it's what @Conley was talking about...

You can use

@require        http://userscripts.org/scripts/source/85365.user.js

which is an modified version to work on Greasemonkey, and then get the jQuery object

var $ = unsafeWindow.jQuery;
$("div").css("display", "none");

Should I use Java's String.format() if performance is important?

Generally you should use String.Format because it's relatively fast and it supports globalization (assuming you're actually trying to write something that is read by the user). It also makes it easier to globalize if you're trying to translate one string versus 3 or more per statement (especially for languages that have drastically different grammatical structures).

Now if you never plan on translating anything, then either rely on Java's built in conversion of + operators into StringBuilder. Or use Java's StringBuilder explicitly.

$date + 1 year?

To add one year to todays date use the following:

$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365 day"));

For the other examples you must initialize $StartingDate with a timestamp value for example:

$StartingDate = mktime();  // todays date as a timestamp

Try this

$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 365 day"));

or

$newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($StaringDate)) . " + 1 year"));

Webview load html from assets directory

Whenever you are creating activity, you must add setcontentview(your layout) after super call. Because setcontentview bind xml into your activity so that's the reason you are getting nullpointerexception.

 setContentView(R.layout.webview);  
 webView = (WebView) findViewById(R.id.webView1);
 wv.loadUrl("file:///android_asset/xyz.html");

How do I call an Angular 2 pipe with multiple arguments?

I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.

Here is the Pipe being called in an *ngFor directive,

<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
  Hello {{item.first}} !
</div>

Here is the Pipe,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
  transform(myobjects: Array<object>, args?: Array<object>): any {
    if (args && Array.isArray(myobjects)) {
      // copy all objects of original array into new array of objects
      var returnobjects = myobjects;
      // args are the compare oprators provided in the *ngFor directive
      args.forEach(function (filterobj) {
        let filterkey = Object.keys(filterobj)[0];
        let filtervalue = filterobj[filterkey];
        myobjects.forEach(function (objectToFilter) {
          if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
            // object didn't match a filter value so remove it from array via filter
            returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
          }
        })
      });
      // return new array of objects to *ngFor directive
      return returnobjects;
    }
  }
}

And here is the Component containing the object to filter,

import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  items = [{ title: "mr", first: "john", last: "jones" }
   ,{ title: "mr", first: "adrian", last: "jacobs" }
   ,{ title: "mr", first: "lou", last: "jones" }
   ,{ title: "ms", first: "linda", last: "hamilton" }
  ];
}

StackBlitz Example

GitHub Example: Fork a working copy of this example here

*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.

Happy Coding :-)

How can I group by date time column without taking time into consideration

GROUP BY DATEADD(day, DATEDIFF(day, 0, MyDateTimeColumn), 0)

Or in SQL Server 2008 onwards you could simply cast to Date as @Oded suggested:

GROUP BY CAST(orderDate AS DATE)

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case I was getting this error because the option (HttpActivation) was not enabled. Windows features dialog box showing HTTP Activation under WCF Services under .NET Framework 4.6 Advanced Services

How do you create vectors with specific intervals in R?

In R the equivalent function is seq and you can use it with the option by:

seq(from = 5, to = 100, by = 5)
# [1]   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  80  85  90  95 100

In addition to by you can also have other options such as length.out and along.with.

length.out: If you want to get a total of 10 numbers between 0 and 1, for example:

seq(0, 1, length.out = 10)
# gives 10 equally spaced numbers from 0 to 1

along.with: It takes the length of the vector you supply as input and provides a vector from 1:length(input).

seq(along.with=c(10,20,30))
# [1] 1 2 3

Although, instead of using the along.with option, it is recommended to use seq_along in this case. From the documentation for ?seq

seq is generic, and only the default method is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

seq_along: Instead of seq(along.with(.))

seq_along(c(10,20,30))
# [1] 1 2 3

Hope this helps.

What is the email subject length limit?

RFC2322 states that the subject header "has no length restriction"

but to produce long headers but you need to split it across multiple lines, a process called "folding".

subject is defined as "unstructured" in RFC 5322

here's some quotes ([...] indicate stuff i omitted)

3.6.5. Informational Fields
  The informational fields are all optional.  The "Subject:" and
  "Comments:" fields are unstructured fields as defined in section
  2.2.1, [...]

2.2.1. Unstructured Header Field Bodies
  Some field bodies in this specification are defined simply as
  "unstructured" (which is specified in section 3.2.5 as any printable
  US-ASCII characters plus white space characters) with no further
  restrictions.  These are referred to as unstructured field bodies.
  Semantically, unstructured field bodies are simply to be treated as a
  single line of characters with no further processing (except for
  "folding" and "unfolding" as described in section 2.2.3).

2.2.3  [...]  An unfolded header field has no length restriction and
  therefore may be indeterminately long.

How to pass a PHP variable using the URL

I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.

Inside "page1.php" or "page1.html":

// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a> 

    //or as I needed it.
    <a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>

Inside "page2c.php":

<?php
    // Retrieve the URL variables (using PHP).
    $num = $_GET['myNumber'];
    $fruit = $_GET['myFruit'];
    echo "Number: ".$num."  Fruit: ".$fruit;
?>

How to convert a string of numbers to an array of numbers?

Matt Zeunert's version with use arraw function (ES6)

const nums = a.split(',').map(x => parseInt(x, 10));

Does JavaScript have a built in stringbuilder class?

No, there is no built-in support for building strings. You have to use concatenation instead.

You can, of course, make an array of different parts of your string and then call join() on that array, but it then depends on how the join is implemented in the JavaScript interpreter you are using.

I made an experiment to compare the speed of str1+str2 method versus array.push(str1, str2).join() method. The code was simple:

var iIterations =800000;
var d1 = (new Date()).valueOf();
str1 = "";
for (var i = 0; i<iIterations; i++)
    str1 = str1 + Math.random().toString();
var d2 = (new Date()).valueOf();
log("Time (strings): " + (d2-d1));

var d3 = (new Date()).valueOf();
arr1 = [];
for (var i = 0; i<iIterations; i++)
    arr1.push(Math.random().toString());
var str2 = arr1.join("");
var d4 = (new Date()).valueOf();
log("Time (arrays): " + (d4-d3));

I tested it in Internet Explorer 8 and Firefox 3.5.5, both on a Windows 7 x64.

In the beginning I tested on small number of iterations (some hundred, some thousand items). The results were unpredictable (sometimes string concatenation took 0 milliseconds, sometimes it took 16 milliseconds, the same for array joining).

When I increased the count to 50,000, the results were different in different browsers - in Internet Explorer the string concatenation was faster (94 milliseconds) and join was slower(125 milliseconds), while in Firefox the array join was faster (113 milliseconds) than string joining (117 milliseconds).

Then I increased the count to 500'000. Now the array.join() was slower than string concatenation in both browsers: string concatenation was 937 ms in Internet Explorer, 1155 ms in Firefox, array join 1265 in Internet Explorer, and 1207 ms in Firefox.

The maximum iteration count I could test in Internet Explorer without having "the script is taking too long to execute" was 850,000. Then Internet Explorer was 1593 for string concatenation and 2046 for array join, and Firefox had 2101 for string concatenation and 2249 for array join.

Results - if the number of iterations is small, you can try to use array.join(), as it might be faster in Firefox. When the number increases, the string1+string2 method is faster.

UPDATE

I performed the test on Internet Explorer 6 (Windows XP). The process stopped to respond immediately and never ended, if I tried the test on more than 100,000 iterations. On 40,000 iterations the results were

Time (strings): 59175 ms
Time (arrays): 220 ms

This means - if you need to support Internet Explorer 6, choose array.join() which is way faster than string concatenation.

Resize jqGrid when browser is resized?

The main answer worked for me but made the app extremely unresponsive in IE, so I used a timer as suggested. Code looks something like this ($(#contentColumn) is the div that the JQGrid sits in):

  function resizeGrids() {
    var reportObjectsGrid = $("#ReportObjectsGrid");
    reportObjectsGrid.setGridWidth($("#contentColumn").width());
};

var resizeTimer;

$(window).bind('resize', function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeGrids, 60);
});

Redirect to specified URL on PHP script completion?

You could always just use the tag to refresh the page - or maybe just drop the necessary javascript into the page at the end that would cause the page to redirect. You could even throw that in an onload function, so once its finished, the page is redirected

<?php

  echo $htmlHeader;
  while($stuff){
    echo $stuff;
  }
  echo "<script>window.location = 'http://www.yourdomain.com'</script>";
?>

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

How to automatically generate unique id in SQL like UID12345678?

Table Creating

create table emp(eno int identity(100001,1),ename varchar(50))

Values inserting

insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')

Select Table

select * from emp

Output

eno     ename
100001  narendra
100002  rama
100003  ajay
100004  anil
100005  raju

Implement an input with a mask

You can also try my implementation, which doesn't have delay after each key press when typing the contents, and has full support for backspace and delete.

You can try it online: https://jsfiddle.net/qmyo6a1h/1/

    <html>
    <style>
    input{
      font-family:'monospace';
    }
    </style>
    <body>
      <input type="text" id="phone" placeholder="123-5678-1234" title="123-5678-1234" input-mask="___-____-____">
      <input type="button" onClick="showValue_phone()" value="Show Value" />
      <input type="text" id="console_phone" />
      <script>
        function InputMask(element) {
          var self = this;

          self.element = element;

          self.mask = element.attributes["input-mask"].nodeValue;

          self.inputBuffer = "";

          self.cursorPosition = 0;

          self.bufferCursorPosition = 0;

          self.dataLength = getDataLength();

          function getDataLength() {
            var ret = 0;

            for (var i = 0; i < self.mask.length; i++) {
              if (self.mask.charAt(i) == "_") {
                ret++;
              }
            }

            return ret;
          }

          self.keyEventHandler = function (obj) {
            obj.preventDefault();

            self.updateBuffer(obj);
            self.manageCursor(obj);
            self.render();
            self.moveCursor();
          }

          self.updateBufferPosition = function () {
            var selectionStart = self.element.selectionStart;
            self.bufferCursorPosition = self.displayPosToBufferPos(selectionStart);
            console.log("self.bufferCursorPosition==" + self.bufferCursorPosition);
          }

          self.onClick = function () {
            self.updateBufferPosition();
          }

          self.updateBuffer = function (obj) {
            if (obj.keyCode == 8) {
              self.inputBuffer = self.inputBuffer.substring(0, self.bufferCursorPosition - 1) + self.inputBuffer.substring(self.bufferCursorPosition);
            }
            else if (obj.keyCode == 46) {
              self.inputBuffer = self.inputBuffer.substring(0, self.bufferCursorPosition) + self.inputBuffer.substring(self.bufferCursorPosition + 1);
            }
            else if (obj.keyCode >= 37 && obj.keyCode <= 40) {
              //do nothing on cursor keys.
            }
            else {
              var selectionStart = self.element.selectionStart;
              var bufferCursorPosition = self.displayPosToBufferPos(selectionStart);
              self.inputBuffer = self.inputBuffer.substring(0, bufferCursorPosition) + String.fromCharCode(obj.which) + self.inputBuffer.substring(bufferCursorPosition);
              if (self.inputBuffer.length > self.dataLength) {
                self.inputBuffer = self.inputBuffer.substring(0, self.dataLength);
              }
            }
          }

          self.manageCursor = function (obj) {
            console.log(obj.keyCode);
            if (obj.keyCode == 8) {
              self.bufferCursorPosition--;
            }
            else if (obj.keyCode == 46) {
              //do nothing on delete key.
            }
            else if (obj.keyCode >= 37 && obj.keyCode <= 40) {
              if (obj.keyCode == 37) {
                self.bufferCursorPosition--;
              }
              else if (obj.keyCode == 39) {
                self.bufferCursorPosition++;
              }
            }
            else {
              var bufferCursorPosition = self.displayPosToBufferPos(self.element.selectionStart);
              self.bufferCursorPosition = bufferCursorPosition + 1;
            }
          }

          self.setCursorByBuffer = function (bufferCursorPosition) {
            var displayCursorPos = self.bufferPosToDisplayPos(bufferCursorPosition);
            self.element.setSelectionRange(displayCursorPos, displayCursorPos);
          }

          self.moveCursor = function () {
            self.setCursorByBuffer(self.bufferCursorPosition);
          }

          self.render = function () {
            var bufferCopy = self.inputBuffer;
            var ret = {
              muskifiedValue: ""
            };

            var lastChar = 0;

            for (var i = 0; i < self.mask.length; i++) {
              if (self.mask.charAt(i) == "_" &&
                bufferCopy) {
                ret.muskifiedValue += bufferCopy.charAt(0);
                bufferCopy = bufferCopy.substr(1);
                lastChar = i;
              }
              else {
                ret.muskifiedValue += self.mask.charAt(i);
              }
            }

            self.element.value = ret.muskifiedValue;

          }

          self.preceedingMaskCharCount = function (displayCursorPos) {
            var lastCharIndex = 0;
            var ret = 0;

            for (var i = 0; i < self.element.value.length; i++) {
              if (self.element.value.charAt(i) == "_"
                || i > displayCursorPos - 1) {
                lastCharIndex = i;
                break;
              }
            }

            if (self.mask.charAt(lastCharIndex - 1) != "_") {
              var i = lastCharIndex - 1;
              while (self.mask.charAt(i) != "_") {
                i--;
                if (i < 0) break;
                ret++;
              }
            }

            return ret;
          }

          self.leadingMaskCharCount = function (displayIndex) {
            var ret = 0;

            for (var i = displayIndex; i >= 0; i--) {
              if (i >= self.mask.length) {
                continue;
              }
              if (self.mask.charAt(i) != "_") {
                ret++;
              }
            }

            return ret;
          }

          self.bufferPosToDisplayPos = function (bufferIndex) {
            var offset = 0;
            var indexInBuffer = 0;

            for (var i = 0; i < self.mask.length; i++) {
              if (indexInBuffer > bufferIndex) {
                break;
              }

              if (self.mask.charAt(i) != "_") {
                offset++;
                continue;
              }

              indexInBuffer++;
            }
            var ret = bufferIndex + offset;

            return ret;
          }

          self.displayPosToBufferPos = function (displayIndex) {
            var offset = 0;
            var indexInBuffer = 0;

            for (var i = 0; i < self.mask.length && i <= displayIndex; i++) {
              if (indexInBuffer >= self.inputBuffer.length) {
                break;
              }

              if (self.mask.charAt(i) != "_") {
                offset++;
                continue;
              }

              indexInBuffer++;
            }

            return displayIndex - offset;
          }

          self.getValue = function () {
            return this.inputBuffer;
          }
          self.element.onkeypress = self.keyEventHandler;
          self.element.onclick = self.onClick;
        }

        function InputMaskManager() {
          var self = this;

          self.instances = {};

          self.add = function (id) {
            var elem = document.getElementById(id);
            var maskInstance = new InputMask(elem);
            self.instances[id] = maskInstance;
          }

          self.getValue = function (id) {
            return self.instances[id].getValue();
          }

          document.onkeydown = function (obj) {
            if (obj.target.attributes["input-mask"]) {
              if (obj.keyCode == 8 ||
                obj.keyCode == 46 ||
                (obj.keyCode >= 37 && obj.keyCode <= 40)) {

                if (obj.keyCode == 8 || obj.keyCode == 46) {
                  obj.preventDefault();
                }

                //needs to broadcast to all instances here:
                var keys = Object.keys(self.instances);
                for (var i = 0; i < keys.length; i++) {
                  if (self.instances[keys[i]].element.id == obj.target.id) {
                    self.instances[keys[i]].keyEventHandler(obj);
                  }
                }
              }
            }
          }
        }

        //Initialize an instance of InputMaskManager and
        //add masker instances by passing in the DOM ids
        //of each HTML counterpart.
        var maskMgr = new InputMaskManager();
        maskMgr.add("phone");

        function showValue_phone() {
          //-------------------------------------------------------__Value_Here_____
          document.getElementById("console_phone").value = maskMgr.getValue("phone");
        }
      </script>
    </body>

    </html>

Critical t values in R

Josh's comments are spot on. If you are not super familiar with critical values I'd suggest playing with qt, reading the manual (?qt) in conjunction with looking at a look up table (LINK). When I first moved from SPSS to R I created a function that made critical t value look up pretty easy (I'd never use this now as it takes too much time and with the p values that are generally provided in the output it's a moot point). Here's the code for that:

critical.t <- function(){
    cat("\n","\bEnter Alpha Level","\n")
    alpha<-scan(n=1,what = double(0),quiet=T)
    cat("\n","\b1 Tailed or 2 Tailed:\nEnter either 1 or 2","\n")
    tt <- scan(n=1,what = double(0),quiet=T)
    cat("\n","\bEnter Number of Observations","\n")
    n <- scan(n=1,what = double(0),quiet=T)
    cat("\n\nCritical Value =",qt(1-(alpha/tt), n-2), "\n")
}

critical.t()

No resource found - Theme.AppCompat.Light.DarkActionBar

In Eclipse: When importing a support library as a project library following the instructions at Adding Support Libraries, don't forget to check the option "Copy proyects into workspace"!

what do <form action="#"> and <form method="post" action="#"> do?

The # tag lets you send your data to the same file. I see it as a three step process:

  1. Query a DB to populate a from
  2. Allow the user to change data in the form
  3. Resubmit the data to the DB via the php script

With the method='#' you can do all of this in the same file.

After the submit query is executed the page will reload with the updated data from the DB.

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

How to check which locks are held on a table

You can find details via the below script.

-- List all Locks of the Current Database 
SELECT TL.resource_type AS ResType 
      ,TL.resource_description AS ResDescr 
      ,TL.request_mode AS ReqMode 
      ,TL.request_type AS ReqType 
      ,TL.request_status AS ReqStatus 
      ,TL.request_owner_type AS ReqOwnerType 
      ,TAT.[name] AS TransName 
      ,TAT.transaction_begin_time AS TransBegin 
      ,DATEDIFF(ss, TAT.transaction_begin_time, GETDATE()) AS TransDura 
      ,ES.session_id AS S_Id 
      ,ES.login_name AS LoginName 
      ,COALESCE(OBJ.name, PAROBJ.name) AS ObjectName 
      ,PARIDX.name AS IndexName 
      ,ES.host_name AS HostName 
      ,ES.program_name AS ProgramName 
FROM sys.dm_tran_locks AS TL 
     INNER JOIN sys.dm_exec_sessions AS ES 
         ON TL.request_session_id = ES.session_id 
     LEFT JOIN sys.dm_tran_active_transactions AS TAT 
         ON TL.request_owner_id = TAT.transaction_id 
            AND TL.request_owner_type = 'TRANSACTION' 
     LEFT JOIN sys.objects AS OBJ 
         ON TL.resource_associated_entity_id = OBJ.object_id 
            AND TL.resource_type = 'OBJECT' 
     LEFT JOIN sys.partitions AS PAR 
         ON TL.resource_associated_entity_id = PAR.hobt_id 
            AND TL.resource_type IN ('PAGE', 'KEY', 'RID', 'HOBT') 
     LEFT JOIN sys.objects AS PAROBJ 
         ON PAR.object_id = PAROBJ.object_id 
     LEFT JOIN sys.indexes AS PARIDX 
         ON PAR.object_id = PARIDX.object_id 
            AND PAR.index_id = PARIDX.index_id 
WHERE TL.resource_database_id  = DB_ID() 
      AND ES.session_id <> @@Spid -- Exclude "my" session 
      -- optional filter  
      AND TL.request_mode <> 'S' -- Exclude simple shared locks 
ORDER BY TL.resource_type 
        ,TL.request_mode 
        ,TL.request_type 
        ,TL.request_status 
        ,ObjectName 
        ,ES.login_name;



--TSQL commands
SELECT 
       db_name(rsc_dbid) AS 'DATABASE_NAME',
       case rsc_type when 1 then 'null'
                             when 2 then 'DATABASE' 
                             WHEN 3 THEN 'FILE'
                             WHEN 4 THEN 'INDEX'
                             WHEN 5 THEN 'TABLE'
                             WHEN 6 THEN 'PAGE'
                             WHEN 7 THEN 'KEY'
                             WHEN 8 THEN 'EXTEND'
                             WHEN 9 THEN 'RID ( ROW ID)'
                             WHEN 10 THEN 'APPLICATION' end  AS 'REQUEST_TYPE',

       CASE req_ownertype WHEN 1 THEN 'TRANSACTION'
                                     WHEN 2 THEN 'CURSOR'
                                     WHEN 3 THEN 'SESSION'
                                     WHEN 4 THEN 'ExSESSION' END AS 'REQUEST_OWNERTYPE',

       OBJECT_NAME(rsc_objid ,rsc_dbid) AS 'OBJECT_NAME', 
       PROCESS.HOSTNAME , 
       PROCESS.program_name , 
       PROCESS.nt_domain , 
       PROCESS.nt_username , 
       PROCESS.program_name ,
       SQLTEXT.text 
FROM sys.syslockinfo LOCK JOIN 
     sys.sysprocesses PROCESS
  ON LOCK.req_spid = PROCESS.spid
CROSS APPLY sys.dm_exec_sql_text(PROCESS.SQL_HANDLE) SQLTEXT
where 1=1
and db_name(rsc_dbid) = db_name()



--Lock on a specific object
SELECT * 
FROM sys.dm_tran_locks
WHERE resource_database_id = DB_ID()
AND resource_associated_entity_id = object_id('Specific Table');

Undefined index with $_POST

try

if(isset($_POST['username']))
    echo $_POST['username']." is your username";
else
    echo "no username supplied";

What does void* mean and how to use it?

C is remarkable in this regard. One can say void is nothingness void* is everything (can be everything).

It's just this tiny * which makes the difference.

Rene has pointed it out. A void * is a Pointer to some location. What there is how to "interpret" is left to the user.

It's the only way to have opaque types in C. Very prominent examples can be found e.g in glib or general data structure libraries. It's treated very detailed in "C Interfaces and implementations".

I suggest you read the complete chapter and try to understand the concept of a pointer to "get it".

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

Animate change of view background color on Android

best way is to use ValueAnimator and ColorUtils.blendARGB

 ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
 valueAnimator.setDuration(325);
 valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {

              float fractionAnim = (float) valueAnimator.getAnimatedValue();

              view.setBackgroundColor(ColorUtils.blendARGB(Color.parseColor("#FFFFFF")
                                    , Color.parseColor("#000000")
                                    , fractionAnim));
        }
});
valueAnimator.start();

How can I use the python HTMLParser library to extract data from a specific div tag?

Have You tried BeautifulSoup ?

from bs4 import BeautifulSoup
soup = BeautifulSoup('<div id="remository">20</div>')
tag=soup.div
print(tag.string)

This gives You 20 on output.

Difference between size and length methods?

length is constant which is used to find out the array storing capacity not the number of elements in the array

Example:

int[] a = new int[5]

a.length always returns 5, which is called the capacity of an array. But

number of elements in the array is called size

Example:

int[] a = new int[5]
a[0] = 10

Here the size would be 1, but a.length is still 5. Mind that there is no actual property or method called size on an array so you can't just call a.size or a.size() to get the value 1.

The size() method is available for collections, length works with arrays in Java.

How to position a Bootstrap popover?

This works. Tested.

.popover {
    top: 71px !important;
    left: 379px !important;
}

draw diagonal lines in div background with CSS

All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:

_x000D_
_x000D_
.crossed {_x000D_
    position: relative;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.crossed:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 1px;_x000D_
    bottom: 1px;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: black white;_x000D_
}_x000D_
_x000D_
.crossed:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 1px;_x000D_
    right: 1px;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: white transparent;_x000D_
}
_x000D_
<div class='crossed'></div>
_x000D_
_x000D_
_x000D_

Explanation, as requested:

Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative space triangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:

_x000D_
_x000D_
.r1 { width: 10px;_x000D_
      height: 0;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: red blue;_x000D_
      margin-bottom: 10px; }_x000D_
.r2 { width: 0;_x000D_
      height: 10px;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: blue transparent; }
_x000D_
<div class='r1'></div><div class='r2'></div>
_x000D_
_x000D_
_x000D_

Finally, use the :before and :after pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.

Putting HTML inside Html.ActionLink(), plus No Link Text?

Here is (low and dirty) workaround in case you need to use ajax or some feature which you cannot use when making link manually (using tag):

<%= Html.ActionLink("LinkTextToken", "ActionName", "ControllerName").ToHtmlString().Replace("LinkTextToken", "Refresh <span class='large sprite refresh'></span>")%>

You can use any text instead of 'LinkTextToken', it is there only to be replaced, it is only important that it does not occur anywhere else inside actionlink.

Server unable to read htaccess file, denying access to be safe

Just my solution. I had extracted a file, had some minor changes, and got the error above. Deleted everything, uploaded and extracted again, and normal business.

How to get the next auto-increment id in mysql

You can't use the ID while inserting, neither do you need it. MySQL does not even know the ID when you are inserting that record. You could just save "sahf4d2fdd45" in the payment_code table and use id and payment_code later on.

If you really need your payment_code to have the ID in it then UPDATE the row after the insert to add the ID.

Action Image MVC3 Razor

To add to all the Awesome work started by Luke I am posting one more that takes a css class value and treats class and alt as optional parameters (valid under ASP.NET 3.5+). This will allow more functionality but reduct the number of overloaded methods needed.

// Extension method
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action,
        string controllerName, object routeValues, string imagePath, string alt = null, string cssClass = null)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        if(alt != null)
            imgBuilder.MergeAttribute("alt", alt);
        if (cssClass != null)
            imgBuilder.MergeAttribute("class", cssClass);

        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");

        anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return MvcHtmlString.Create(anchorHtml);
    }

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

SSIS Text was truncated with status value 4

I suspect the or one or more characters had no match in the target code page part of the error.

If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

How do I parse command line arguments in Bash?

There are several ways to parse cmdline args (e.g. GNU getopt (not portable) vs BSD (MacOS) getopt vs getopts) - all problematic. This solution

  • is portable!
  • has zero dependencies, only relies on bash built-ins
  • allows for both short and long options
  • handles whitespace or simultaneously the use of = separator between option and argument
  • supports concatenated short option style -vxf
  • handles option with optional arguments (E.g. --color vs --color=always),
  • correctly detects and reports unknown options
  • supports -- to signal end of options, and
  • doesn't require code bloat compared with alternatives for the same feature set. I.e. succinct, and therefore easier to maintain

Examples: Any of

# flag
-f
--foo

# option with required argument
-b"Hello World"
-b "Hello World"
--bar "Hello World"
--bar="Hello World"

# option with optional argument
--baz
--baz="Optional Hello"

#!/usr/bin/env bash

usage() {
  cat - >&2 <<EOF
NAME
    program-name.sh - Brief description
 
SYNOPSIS
    program-name.sh [-h|--help]
    program-name.sh [-f|--foo]
                    [-b|--bar <arg>]
                    [--baz[=<arg>]]
                    [--]
                    FILE ...

REQUIRED ARGUMENTS
  FILE ...
          input files

OPTIONS
  -h, --help
          Prints this and exits

  -f, --foo
          A flag option
      
  -b, --bar <arg>
          Option requiring an argument <arg>

  --baz[=<arg>]
          Option that has an optional argument <arg>. If <arg>
          is not specified, defaults to 'DEFAULT'
  --     
          Specify end of options; useful if the first non option
          argument starts with a hyphen

EOF
}

fatal() {
    for i; do
        echo -e "${i}" >&2
    done
    exit 1
}

# For long option processing
next_arg() {
    if [[ $OPTARG == *=* ]]; then
        # for cases like '--opt=arg'
        OPTARG="${OPTARG#*=}"
    else
        # for cases like '--opt arg'
        OPTARG="${args[$OPTIND]}"
        OPTIND=$((OPTIND + 1))
    fi
}

# ':' means preceding option character expects one argument, except
# first ':' which make getopts run in silent mode. We handle errors with
# wildcard case catch. Long options are considered as the '-' character
optspec=":hfb:-:"
args=("" "$@")  # dummy first element so $1 and $args[1] are aligned
while getopts "$optspec" optchar; do
    case "$optchar" in
        h) usage; exit 0 ;;
        f) foo=1 ;;
        b) bar="$OPTARG" ;;
        -) # long option processing
            case "$OPTARG" in
                help)
                    usage; exit 0 ;;
                foo)
                    foo=1 ;;
                bar|bar=*) next_arg
                    bar="$OPTARG" ;;
                baz)
                    baz=DEFAULT ;;
                baz=*) next_arg
                    baz="$OPTARG" ;;
                -) break ;;
                *) fatal "Unknown option '--${OPTARG}'" "see '${0} --help' for usage" ;;
            esac
            ;;
        *) fatal "Unknown option: '-${OPTARG}'" "See '${0} --help' for usage" ;;
    esac
done

shift $((OPTIND-1))

if [ "$#" -eq 0 ]; then
    fatal "Expected at least one required argument FILE" \
    "See '${0} --help' for usage"
fi

echo "foo=$foo, bar=$bar, baz=$baz, files=${@}"

How to check if there exists a process with a given pid in Python?

Have a look at the psutil module:

psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python. [...] It currently supports Linux, Windows, OSX, FreeBSD and Sun Solaris, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.4 (users of Python 2.4 and 2.5 may use 2.1.3 version). PyPy is also known to work.

It has a function called pid_exists() that you can use to check whether a process with the given pid exists.

Here's an example:

import psutil
pid = 12345
if psutil.pid_exists(pid):
    print("a process with pid %d exists" % pid)
else:
    print("a process with pid %d does not exist" % pid)

For reference:

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

What is a lambda (function)?

The name "lambda" is just a historical artifact. All we're talking about is an expression whose value is a function.

A simple example (using Scala for the next line) is:

args.foreach(arg => println(arg))

where the argument to the foreach method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you'll get the idea):

void printThat(Object that) {
  println(that)
}
...
args.foreach(printThat)

except that you don't need to bother with:

  1. Declaring the function somewhere else (and having to look for it when you revisit the code later).
  2. Naming something that you're only using once.

Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:

int tempVar = 2 * a + b
...
println(tempVar)

instead of just writing the expression where you need it:

println(2 * a + b)

The exact notation varies from language to language; Greek isn't always required! ;-)

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

  • pyenv - manages different python versions,
  • all others - create virtual environment (which has isolated python version and installed "requirements"),

pipenv want combine all, in addition to previous it installs "requirements" (into the active virtual environment or create its own if none is active)

So maybe you will be happy with pipenv only.

But I use: pyenv + pyenv-virtualenvwrapper, + pipenv (pipenv for installing requirements only).

In Debian:

  1. apt install libffi-dev

  2. install pyenv based on https://www.tecmint.com/pyenv-install-and-manage-multiple-python-versions-in-linux/, but..

  3. .. but instead of pyenv-virtualenv install pyenv-virtualenvwrapper (which can be standalone library or pyenv plugin, here the 2nd option):

    pyenv install 3.9.0

    git clone https://github.com/pyenv/pyenv-virtualenvwrapper.git $(pyenv root)/plugins/pyenv-virtualenvwrapper

    into ~/.bashrc add: export $VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"

    source ~/.bashrc

    pyenv virtualenvwrapper

Then create virtual environments for your projects (workingdir must exist):

pyenv local 3.9.0  # to prevent 'interpreter not found' in mkvirtualenv
python -m pip install --upgrade pip setuptools wheel
mkvirtualenv <venvname> -p python3.9 -a <workingdir>

and switch between projects:

workon <venvname>
python -m pip install --upgrade pip setuptools wheel pipenv

Inside a project I have the file requirements.txt, without fixing the versions inside (if some version limitation is not neccessary). You have 2 possible tools to install them into the current virtual environment: pip-tools or pipenv. Lets say you will use pipenv:

pipenv install -r requirements.txt

this will create Pipfile and Pipfile.lock files, fixed versions are in the 2nd one. If you want reinstall somewhere exactly same versions then (Pipfile.lock must be present):

pipenv install

Remember that Pipfile.lock is related to some Python version and need to be recreated if you use a different one.

As you see I write requirements.txt. This has some problems: You must remove a removed package from Pipfile too. So writing Pipfile directly is probably better.

So you can see I use pipenv very poorly. Maybe if you will use it well, it can replace everything?

EDIT 2021.01: I have changed my stack to: pyenv + pyenv-virtualenvwrapper + poetry. Ie. I use no apt or pip installation of virtualenv or virtualenvwrapper, and instead I install pyenv's plugin pyenv-virtualenvwrapper. This is easier way.

Poetry is great for me:

poetry add <package>   # install single package
poetry remove <package>
poetry install   # if you remove poetry.lock poetry will re-calculate versions

php error: Class 'Imagick' not found

From: http://news.ycombinator.com/item?id=1726074

For RHEL-based i386 distributions:

yum install ImageMagick.i386
yum install ImageMagick-devel.i386
pecl install imagick
echo "extension=imagick.so" > /etc/php.d/imagick.ini
service httpd restart

This may also work on other i386 distributions using yum package manager. For x86_64, just replace .i386 with .x86_64

Tracking CPU and Memory usage per process

Process Explorer can show total CPU time taken by a process, as well as a history graph per process.

How do I encode URI parameter values?

It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.

jQuery load first 3 elements, click "load more" to display next 5 elements

The expression $(document).ready(function() deprecated in jQuery3.

See working fiddle with jQuery 3 here

Take into account I didn't include the showless button.

Here's the code:

JS

$(function () {
    x=3;
    $('#myList li').slice(0, 3).show();
    $('#loadMore').on('click', function (e) {
        e.preventDefault();
        x = x+5;
        $('#myList li').slice(0, x).slideDown();
    });
});

CSS

#myList li{display:none;
}
#loadMore {
    color:green;
    cursor:pointer;
}
#loadMore:hover {
    color:black;
}

Delete a dictionary item if the key exists

You can use dict.pop:

 mydict.pop("key", None)

Note that if the second argument, i.e. None is not given, KeyError is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.

How to create a zip file in Java

Single file:

String filePath = "/absolute/path/file1.txt";
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    File fileToZip = new File(filePath);
    zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
    Files.copy(fileToZip.toPath(), zipOut);
}

Multiple files:

List<String> filePaths = Arrays.asList("/absolute/path/file1.txt", "/absolute/path/file2.txt");
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    for (String filePath : filePaths) {
        File fileToZip = new File(filePath);
        zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
        Files.copy(fileToZip.toPath(), zipOut);
    }
}

What is the meaning of "Failed building wheel for X" in pip install?

(pip maintainer here!)

If the package is not a wheel, pip tries to build a wheel for it (via setup.py bdist_wheel). If that fails for any reason, you get the "Failed building wheel for pycparser" message and pip falls back to installing directly (via setup.py install).

Once we have a wheel, pip can install the wheel by unpacking it correctly. pip tries to install packages via wheels as often as it can. This is because of various advantages of using wheels (like faster installs, cache-able, not executing code again etc).


Your error message here is due to the wheel package being missing, which contains the logic required to build the wheels in setup.py bdist_wheel. (pip install wheel can fix that.)


The above is the legacy behavior that is currently the default; we'll switch to PEP 517 by default, sometime in the future, moving us to a standards-based process for this. We also have isolated builds for that so, you'd have wheel installed in those environments by default. :)

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

Parse JSON from HttpURLConnection object

This function will be used get the data from url in form of HttpResponse object.

public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}

Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.

String jsonString     =     
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
                    jsonElementForJavaObject, JsonJavaModel.class);

This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:

public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {

@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
                                 JsonDeserializationContext arg2) throws    JsonParseException {
    final JsonJavaModel jsonJavaModel= new JsonJavaModel();
    JsonObject object = json.getAsJsonObject();

    try {
     jsonJavaModel.content = object.get("Content").getAsString()
     jsonJavaModel.title = object.get("Title").getAsString()

    } catch (Exception e) {

        e.printStackTrace();
    }
    return jsonJavaModel;
}

Include Gson library and org.apache.http.util.EntityUtils;

How to use ng-if to test if a variable is defined

Try this:

item.shipping!==undefined

Will iOS launch my app into the background if it was force-quit by the user?

This might help you

In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.

Source: https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Rotate a div using javascript

I recently had to build something similar. You can check it out in the snippet below.

The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin

Basically, my code looks like this...

Run Code Snippet

_x000D_
_x000D_
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
    runner = setInterval(function(){_x000D_
        degrees++;_x000D_
        rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
    },50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
    clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
    if (!rotate){_x000D_
        rotate = true;_x000D_
        start();_x000D_
    } else {_x000D_
        rotate = false;_x000D_
        stop();_x000D_
    }_x000D_
})
_x000D_
body {_x000D_
  background: #1e1e1e;_x000D_
}    _x000D_
_x000D_
.rocket {_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    margin: 1em;_x000D_
    border: 3px dashed teal;_x000D_
    border-radius: 50%;_x000D_
    background-color: rgba(128,128,128,0.5);_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
  }_x000D_
  _x000D_
  .rocket h1 {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    font-size: .8em;_x000D_
    color: skyblue;_x000D_
    letter-spacing: 1em;_x000D_
    text-shadow: 0 0 10px black;_x000D_
  }_x000D_
  _x000D_
  .toggle {_x000D_
    margin: 10px;_x000D_
    background: #000;_x000D_
    color: white;_x000D_
    font-size: 1em;_x000D_
    padding: .3em;_x000D_
    border: 2px solid red;_x000D_
    outline: none;_x000D_
    letter-spacing: 3px;_x000D_
  }
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
_x000D_
_x000D_

showing that a date is greater than current date

In sql server, you can do

SELECT *
FROM table t
WHERE t.date > DATEADD(dd,90,now())

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

How to make a section of an image a clickable link

The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;
}

Generate an integer sequence in MySQL

Sequence of numbers between 1 and 100.000:

SELECT e*10000+d*1000+c*100+b*10+a n FROM
(select 0 a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t1,
(select 0 b union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2,
(select 0 c union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3,
(select 0 d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4,
(select 0 e union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t5
order by 1

I use it to audit if some number is out of sequence, something like this:

select * from (
    select 121 id
    union all select 123
    union all select 125
    union all select 126
    union all select 127
    union all select 128
    union all select 129
) a
right join (
    SELECT e*10000+d*1000+c*100+b*10+a n FROM
    (select 0 a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t1,
    (select 0 b union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2,
    (select 0 c union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3,
    (select 0 d union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4,
    (select 0 e union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t5
    order by 1
) seq on seq.n=a.id
where seq.n between 121 and 129
and   id is null

The result will be the gap of number 122 and 124 of sequence between 121 and 129:

id     n
----   ---
null   122
null   124

Maybe it helps someone!

How to purge tomcat's cache when deploying a new .war file? Is there a config setting?

I'm new to tomcat, and this problem was driving me nuts today. It was sporadic. I asked a colleague to help, and the WAR expanded and it did was it was supposed to. 3 deploys later that day, it reverted back to the original version.

In my case, the MySite.WAR got expanded to both ROOT AND MySite. MySite was usually served up. But sometimes tomcat decided it liked the ROOT one better and all my changes disappeared.

The "solution" is to delete the ROOT website with every deploy of the war.

Setting the character encoding in form submit for Internet Explorer

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

How to take complete backup of mysql database using mysqldump command line utility

Use these commands :-

mysqldump <other mysqldump options> --routines > outputfile.sql

If we want to backup ONLY the stored procedures and triggers and not the mysql tables and data then we should run something like:

mysqldump --routines --no-create-info --no-data --no-create-db --skip-opt <database> > outputfile.sql

If you need to import them to another db/server you will have to run something like:

mysql <database> < outputfile.sql

Easy way to turn JavaScript array into comma-separated list?

Simple Array

_x000D_
_x000D_
let simpleArray = [1,2,3,4]
let commaSeperated = simpleArray.join(",");
console.log(commaSeperated);
_x000D_
_x000D_
_x000D_

Array of Objects with a particular attributes as comma separated.

_x000D_
_x000D_
let arrayOfObjects = [
{
id : 1,
name : "Name 1",
address : "Address 1"
},
{
id : 2,
name : "Name 2",
address : "Address 2"
},
{
id : 3,
name : "Name 3",
address : "Address 3"
}]
let names = arrayOfObjects.map(x => x.name).join(", ");
console.log(names);
_x000D_
_x000D_
_x000D_

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

How can I search for a multiline pattern in a file?

Using ex/vi editor and globstar option (syntax similar to awk and sed):

ex +"/string1/,/string3/p" -R -scq! file.txt

where aaa is your starting point, and bbb is your ending text.

To search recursively, try:

ex +"/aaa/,/bbb/p" -scq! **/*.py

Note: To enable ** syntax, run shopt -s globstar (Bash 4 or zsh).

Generics/templates in python?

Here's a variant of this answer that uses metaclasses to avoid the messy syntax, and use the typing-style List[int] syntax:

class template(type):
    def __new__(metacls, f):
        cls = type.__new__(metacls, f.__name__, (), {
            '_f': f,
            '__qualname__': f.__qualname__,
            '__module__': f.__module__,
            '__doc__': f.__doc__
        })
        cls.__instances = {}
        return cls

    def __init__(cls, f):  # only needed in 3.5 and below
        pass

    def __getitem__(cls, item):
        if not isinstance(item, tuple):
            item = (item,)
        try:
            return cls.__instances[item]
        except KeyError:
            cls.__instances[item] = c = cls._f(*item)
            item_repr = '[' + ', '.join(repr(i) for i in item) + ']'
            c.__name__ = cls.__name__ + item_repr
            c.__qualname__ = cls.__qualname__ + item_repr
            c.__template__ = cls
            return c

    def __subclasscheck__(cls, subclass):
        for c in subclass.mro():
            if getattr(c, '__template__', None) == cls:
                return True
        return False

    def __instancecheck__(cls, instance):
        return cls.__subclasscheck__(type(instance))

    def __repr__(cls):
        import inspect
        return '<template {!r}>'.format('{}.{}[{}]'.format(
            cls.__module__, cls.__qualname__, str(inspect.signature(cls._f))[1:-1]
        ))

With this new metaclass, we can rewrite the example in the answer I link to as:

@template
def List(member_type):
    class List(list):
        def append(self, member):
            if not isinstance(member, member_type):
                raise TypeError('Attempted to append a "{0}" to a "{1}" which only takes a "{2}"'.format(
                    type(member).__name__,
                    type(self).__name__,
                    member_type.__name__ 
                ))

                list.append(self, member)
    return List

l = List[int]()
l.append(1)  # ok
l.append("one")  # error

This approach has some nice benefits

print(List)  # <template '__main__.List[member_type]'>
print(List[int])  # <class '__main__.List[<class 'int'>, 10]'>
assert List[int] is List[int]
assert issubclass(List[int], List)  # True

How do you format a Date/Time in TypeScript?

One more to add @kamalakar's answer, need to import the same in app.module and add DateFormatPipe to providers.

    import {DateFormatPipe} from './DateFormatPipe';
    @NgModule
    ({ declarations: [],  
        imports: [],
        providers: [DateFormatPipe]
    })

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

I was facing this issue even after supplying all required datasource properties in application.properties. Then I realized that properties configuration class was not getting scanned by Spring boot because it was in different package hierarchy compared to my Spring boot Application.java and hence no properties were applied to datasource object. I changed the package name of my properties configuration class and it started working.

DataTable: How to get item value with row name and column name? (VB)

Try:

DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()

(This is C# code. Change this to VB equivalent)

How do you roll back (reset) a Git repository to a particular commit?

When you say the 'GUI Tool', I assume you're using Git For Windows.

IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.

With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

Merge two json/javascript arrays in to one array

Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2); will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.

What you seek is a simple javascript function known as .concat. Which would work like:

var finalObj = json1.concat(json2);

While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:

;(function($) {
    if (!$.concat) {
        $.extend({
            concat: function() {
                return Array.prototype.concat.apply([], arguments);
            }
        });
    }
})(jQuery);

And then recall it as desired like:

var finalObj = $.concat(json1, json2);

You can also use it for multiple array objects of this type with a like:

var finalObj = $.concat(json1, json2, json3, json4, json5, ....);

And if you really want it jQuery style and very short and sweet (aka minified)

;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);

_x000D_
_x000D_
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);_x000D_
_x000D_
$(function() {_x000D_
    var json1 = [{id:1, name: 'xxx'}],_x000D_
        json2 = [{id:2, name: 'xyz'}],_x000D_
        json3 = [{id:3, name: 'xyy'}],_x000D_
        json4 = [{id:4, name: 'xzy'}],_x000D_
        json5 = [{id:5, name: 'zxy'}];_x000D_
    _x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3));_x000D_
    console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json1, json2, json3, json4, json5));_x000D_
    console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));_x000D_
    console.log($.concat(json4, json1, json2, json5));_x000D_
});
_x000D_
center { padding: 3em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<center>See Console Log</center>
_x000D_
_x000D_
_x000D_

jsFiddle

How to overcome the CORS issue in ReactJS

You can have your React development server proxy your requests to that server. Simply send your requests to your local server like this: url: "/" And add the following line to your package.json file

"proxy": "https://awww.api.com"

Though if you are sending CORS requests to multiple sources, you'll have to manually configure the proxy yourself This link will help you set that up Create React App Proxying API requests

How to get a value of an element by name instead of ID

$('[name=whatever]').val()

The jQuery documentation is your friend.

window.location.reload with clear cache

i had this problem and i solved it using javascript

 location.reload(true);

you may also use

window.history.forward(1);

to stop the browser back button after user logs out of the application.

Convert string to a variable name

Maybe I didn't understand your problem right, because of the simplicity of your example. To my understanding, you have a series of instructions stored in character vectors, and those instructions are very close to being properly formatted, except that you'd like to cast the right member to numeric.

If my understanding is right, I would like to propose a slightly different approach, that does not rely on splitting your original string, but directly evaluates your instruction (with a little improvement).

original_string <- "variable_name=\"10\"" # Your original instruction, but with an actual numeric on the right, stored as character.
library(magrittr) # Or library(tidyverse), but it seems a bit overkilled if the point is just to import pipe-stream operator
eval(parse(text=paste(eval(original_string), "%>% as.numeric")))
print(variable_name)
#[1] 10

Basically, what we are doing is that we 'improve' your instruction variable_name="10" so that it becomes variable_name="10" %>% as.numeric, which is an equivalent of variable_name=as.numeric("10") with magrittr pipe-stream syntax. Then we evaluate this expression within current environment.

Hope that helps someone who'd wander around here 8 years later ;-)

Oracle: Call stored procedure inside the package

To those that are incline to use GUI:

Click Right mouse button on procecdure name then select Test

enter image description here

Then in new window you will see script generated just add the parameters and click on Start Debugger or F9

enter image description here

Hope this saves you some time.

Combining multiple commits before pushing in Git

What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:

git rebase -i origin/master

This will bring up your text editor (-i is for "interactive") with a file that looks like this:

pick 16b5fcc Code in, tests not passing
pick c964dea Getting closer
pick 06cf8ee Something changed
pick 396b4a3 Tests pass
pick 9be7fdb Better comments
pick 7dba9cb All done

Change all the pick to squash (or s) except the first one:

pick 16b5fcc Code in, tests not passing
squash c964dea Getting closer
squash 06cf8ee Something changed
squash 396b4a3 Tests pass
squash 9be7fdb Better comments
squash 7dba9cb All done

Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.

Voila! Googling "git squashing" will give you explanations of all the other options available.

Explanation of the UML arrows

For quick reference along with clear concise examples, Allen Holub's UML Quick Reference is excellent:

http://www.holub.com/goodies/uml/

(There are quite a few specific examples of arrows and pointers in the first column of a table, with descriptions in the second column.)

:: (double colon) operator in Java 8

In java-8 Streams Reducer in simple works is a function which takes two values as input and returns result after some calculation. this result is fed in next iteration.

in case of Math:max function, method keeps returning max of two values passed and in the end you have largest number in hand.

jQuery - Call ajax every 10 seconds

Are you going to want to do a setInterval()?

setInterval(function(){get_fb();}, 10000);

Or:

setInterval(get_fb, 10000);

Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).success(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Or use .ajax().complete() if you want it to run regardless of result:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).complete(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.

http://jsfiddle.net/YXMPn/

How can I use interface as a C# generic type constraint?

The closest you can do (except for your base-interface approach) is "where T : class", meaning reference-type. There is no syntax to mean "any interface".

This ("where T : class") is used, for example, in WCF to limit clients to service contracts (interfaces).

Appending an id to a list if not already present in a string

7 years later, allow me to give a one-liner solution by building on a previous answer. You could do the followwing:

numbers = [1, 2, 3]

to Add [3, 4, 5] into numbers without repeating 3, do the following:

numbers = list(set(numbers + [3, 4, 5]))

This results in 4 and 5 being added to numbers as in [1, 2, 3, 4, 5]

Explanation:

Now let me explain what happens, starting from the inside of the set() instruction, we took numbers and added 3, 4, and 5 to it which makes numbers look like [1, 2, 3, 3, 4, 5]. Then, we took that ([1, 2, 3, 3, 4, 5]) and transformed it into a set which gets rid of duplicates, resulting in the following {1, 2, 3, 4, 5}. Now since we wanted a list and not a set, we used the function list() to make that set ({1, 2, 3, 4, 5}) into a list, resulting in [1, 2, 3, 4, 5] which we assigned to the variable numbers

This, I believe, will work for all types of data in a list, and objects as well if done correctly.

How do I sort a table in Excel if it has cell references in it?

I had this same problem; I had a master sheet which was a summary of information on other worksheets in my workbook.

If you just want to filter/sort in a worksheet where you have your data stored, and then return it to its original state (no matter what you are filtering/sorting by) just make your first column a Line Item Number.

After your initial filter/sort you can then just resort by the “Line Item Number” to return everything back to normal. NOTE: This only works if you always add new rows to the end of the list in sequence.

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

Receive result from DialogFragment

I'm very surprised to see that no-one has suggested using local broadcasts for DialogFragment to Activity communication! I find it to be so much simpler and cleaner than other suggestions. Essentially, you register for your Activity to listen out for the broadcasts and you send the local broadcasts from your DialogFragment instances. Simple. For a step-by-step guide on how to set it all up, see here.

What is the best way to redirect a page using React Router?

You also can Redirect within the Route as follows. This is for handle invalid routes.

<Route path='*' render={() => 
     (
       <Redirect to="/error"/>
     )
}/>

No increment operator (++) in Ruby?

I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.

Sure you could use $var=0; $var++ in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++ would probably throw an error.

I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.

Detect if Android device has Internet connection

You can use ConnectivityManager.

val cm = getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
            val dialogBuilder = AlertDialog.Builder(this)

            if (activeNetwork!=null) // Some network is available
            {
                if (activeNetwork.isConnected) { // Network is connected to internet

    }else{ // Network is NOT connected to internet

    }

Check this and this

Nested Recycler view height doesn't wrap its content

An alternative to extend LayoutManager can be just set the size of the view manually.

Number of items per row height (if all the items have the same height and the separator is included on the row)

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mListView.getLayoutParams();
params.height = mAdapter.getItemCount() * getResources().getDimensionPixelSize(R.dimen.row_height);
mListView.setLayoutParams(params);

Is still a workaround, but for basic cases it works.

Set the location in iPhone Simulator

Open iOS Simulator application from Debug Menu -> Location ->

  1. None
  2. Custom Location
  3. Apple Stores ...

SyntaxError: missing ; before statement

too many ) parenthesis remove one of them.

Search for a string in Enum and return the Enum

One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided here

With this you can define your enumerations as classes (the examples are in vb.net):

< StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)

Private Sub New(ByVal StrValue As String)
  MyBase.New(StrValue)   
End Sub

< Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP")   

< Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")   

End Class

And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication (inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".

I've been using this for a long time now and it makes the code more clear in intent.

Replace whole line containing a string using Sed

It is as similar to above one..

sed 's/[A-Za-z0-9]*TEXT_TO_BE_REPLACED.[A-Za-z0-9]*/This line is removed by the admin./'

Why am I getting the error "connection refused" in Python? (Sockets)

try this command in terminal:

sudo ufw enable
ufw allow 12397

Convert a row of a data frame to vector

Here is a dplyr based option:

newV = df %>% slice(1) %>% unlist(use.names = FALSE)

# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

In Angular 2x

In example.component.ts

import { Observable } from 'rxjs';

In example.component.html

  Observable.interval(2000).map(valor => 'Async value');

In Angular 5x or Angular 6x:

In example.component.ts

import { Observable, interval, pipe } from 'rxjs';
import {switchMap, map} from 'rxjs/operators';

In example.component.html

valorAsync = interval(2500).pipe(map(valor => 'Async value'));

How to read values from the querystring with ASP.NET Core?

Here is a code sample I've used (with a .NET Core view):

@{
    Microsoft.Extensions.Primitives.StringValues queryVal;

    if (Context.Request.Query.TryGetValue("yourKey", out queryVal) &&
        queryVal.FirstOrDefault() == "yourValue")
    {
    }
}

How to get the second column from command output?

Use -F [field separator] to split the lines on "s:

awk -F '"' '{print $2}' your_input_file

or for input from pipe

<some_command> | awk -F '"' '{print $2}'

output:

A B
C
D

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

In Windows Vista and later the HTTP WCF service stuff would cause the exception you mentioned because a restricted account does not have right for that. That is the reason why it worked when you ran it as administrator.

Every sensible developer must use a RESTRICTED account rather than as an Administrator, yet many people go the wrong way and that is precisely why there are so many applications out there that DEMAND admin permissions when they are not really required. Working the lazy way results in lazy solutions. I hope you still work in a restricted account (my congratulations).

There is a tool out there (from 2008 or so) called NamespaceManagerTool if I remember correctly that is supposed to grant the restricted user permissions on these service URLs that you define for WCF. I haven't used that though...

C - casting int to char and append char to char

Casting int to char involves losing data and the compiler will probably warn you.

Extracting a particular byte from an int sounds more reasonable and can be done like this:

number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */

Android - Spacing between CheckBox and text

This behavior appears to have changed in Jelly Bean. The paddingLeft trick adds additional padding, making the text look too far right. Any one else notice that?

Android WebView not loading an HTTPS URL

Per correct answer by fargth, follows is a small code sample that might help.

First, create a class that extends WebViewClient and which is set to ignore SSL errors:

// SSL Error Tolerant Web View Client
private class SSLTolerentWebViewClient extends WebViewClient {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed(); // Ignore SSL certificate errors
            }

}

Then with your web view object (initiated in the OnCreate() method), set its web view client to be an instance of the override class:

 mWebView.setWebViewClient(
                new SSLTolerentWebViewClient()
        );

How do I make a comment in a Dockerfile?

Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):

# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.

FROM ubuntu
MAINTAINER Kimbro Staken

RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen

#RUN echo "" >> /etc/mongodb.conf

CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"] 

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

There are literal arrowheads in the Spacing Modifier Letters block:

U+02C2  ?   &#706;  Modifier Letter Left  Arrowhead
U+02C3  ?   &#707;  Modifier Letter Right Arrowhead
U+02C4  ^   &#708;  Modifier Letter Up    Arrowhead
U+02C5  ?   &#709;  Modifier Letter Down  Arrowhead

How would I create a UIAlertView in Swift?

 let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
    let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
        print("Default is pressed.....")
    }
    let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel is pressed......")
    }
    let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
        print("Destructive is pressed....")

    }
    alertController.addAction(action1)
    alertController.addAction(action2)
    alertController.addAction(action3)
    self.present(alertController, animated: true, completion: nil)

}

Cache an HTTP 'Get' service response in AngularJS?

Check out the library angular-cache if you like $http's built-in caching but want more control. You can use it to seamlessly augment $http cache with time-to-live, periodic purges, and the option of persisting the cache to localStorage so that it's available across sessions.

FWIW, it also provides tools and patterns for making your cache into a more dynamic sort of data-store that you can interact with as POJO's, rather than just the default JSON strings. Can't comment on the utility of that option as yet.

(Then, on top of that, related library angular-data is sort of a replacement for $resource and/or Restangular, and is dependent upon angular-cache.)

Difference between dangling pointer and memory leak

You can think of these as the opposites of one another.

When you free an area of memory, but still keep a pointer to it, that pointer is dangling:

char *c = malloc(16);
free(c);
c[1] = 'a'; //invalid access through dangling pointer!

When you lose the pointer, but keep the memory allocated, you have a memory leak:

void myfunc()
{
    char *c = malloc(16);
} //after myfunc returns, the the memory pointed to by c is not freed: leak!

How to set Spring profile from system variable?

I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.

*Answering your question, system variable has higher priority *


Getting profile based beans from applicationContext

  • Use @Profile on a Bean

@Component
@Profile("dev")
public class DatasourceConfigForDev

Now, the profile is dev

Note : if the Profile is given as @Profile("!dev") then the profile will exclude dev and be for all others.

  • Use profiles attribute in XML

<beans profile="dev">
    <bean id="DatasourceConfigForDev" class="org.skoolguy.profiles.DatasourceConfigForDev"/>
</beans>

Set the value for profile:

  • Programmatically via WebApplicationInitializer interface

    In web applications, WebApplicationInitializer can be used to configure the ServletContext programmatically
@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.setInitParameter("spring.profiles.active", "dev");
    }
}
  • Programmatically via ConfigurableEnvironment

    You can also set profiles directly on the environment:
    @Autowired
    private ConfigurableEnvironment env;

    // ...

    env.setActiveProfiles("dev");
  • Context Parameter in web.xml

    profiles can be activated in the web.xml of the web application as well, using a context parameter:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-config.xml</param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>
  • JVM System Parameter

    The profile names passed as the parameter will be activated during application start-up:

    -Dspring.profiles.active=dev
    

    In IDEs, you can set the environment variables and values to use when an application runs. The following is the Run Configuration in Eclipse:

Eclipse Run Configuration - screenshot is unavailable

  • Environment Variable

    to set via command line : export spring_profiles_active=dev

Any bean that does not specify a profile belongs to “default” profile.


The priority order is :

  1. Context parameter in web.xml
  2. WebApplicationInitializer
  3. JVM System parameter
  4. Environment variable

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

Angular CLI: 8.3.4 Node : 10.16.3 Angualr : 4.2.5

I used "dotnet new angular" command to generate the project, and it has generated 3 different modules in app folder (Although a simple test with ng new project-name just generates a single module.

see the modules in your project and decide wich module you want - then specify the name

ng g c componentName --module=[name-of-your-module]

You can read more about modules here: https://angular.io/guide/architecture-modules

Turn off textarea resizing

As per the question, i have listed the answers in javascript

By Selecting TagName

document.getElementsByTagName('textarea')[0].style.resize = "none";

By Selecting Id

document.getElementById('textArea').style.resize = "none";

Center an item with position: relative

You can use calc to position element relative to center. For example if you want to position element 200px right from the center .. you can do this :

#your_element{
    position:absolute;
    left: calc(50% + 200px);
}

Dont forget this

When you use signs + and - you must have one blank space between sign and number, but when you use signs * and / there is no need for blank space.

Check if a string has white space

A few others have posted answers. There are some obvious problems, like it returns false when the Regex passes, and the ^ and $ operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).

Besides that, the issue is just a typo.

Change this...

var reWhiteSpace = new RegExp("/^\s+$/");

To this...

var reWhiteSpace = new RegExp("\\s+");

When using a regex within RegExp(), you must do the two following things...

  • Omit starting and ending / brackets.
  • Double-escape all sequences code, i.e., \\s in place of \s, etc.

Full working demo from source code....

_x000D_
_x000D_
$(document).ready(function(e) { function hasWhiteSpace(s) {
        var reWhiteSpace = new RegExp("\\s+");
    
        // Check for white space
        if (reWhiteSpace.test(s)) {
            //alert("Please Check Your Fields For Spaces");
            return 'true';
        }
    
        return 'false';
    }
  
  $('#whitespace1').html(hasWhiteSpace(' '));
  $('#whitespace2').html(hasWhiteSpace('123'));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
" ": <span id="whitespace1"></span><br>
"123": <span id="whitespace2"></span>
_x000D_
_x000D_
_x000D_

Why is Event.target not Element in Typescript?

@Bangonkali provide the right answer, but this syntax seems more readable and just nicer to me:

eventChange($event: KeyboardEvent): void {
    (<HTMLInputElement>$event.target).value;
}

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

I followed the steps detailed in Generating a new SSH key and adding it to the ssh-agent and

Auto-launching ssh-agent on Git for Windows.

In my case ~/.profile file was not present in my Windows. I had to create it, then added the script provided in the above link.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation mappedBy ideally should always be used in the Parent side (Company class) of the bi directional relationship, in this case it should be in Company class pointing to the member variable 'company' of the Child class (Branch class)

The annotation @JoinColumn is used to specify a mapped column for joining an entity association, this annotation can be used in any class (Parent or Child) but it should ideally be used only in one side (either in parent class or in Child class not in both) here in this case i used it in the Child side (Branch class) of the bi directional relationship indicating the foreign key in the Branch class.

below is the working example :

parent class , Company

@Entity
public class Company {


    private int companyId;
    private String companyName;
    private List<Branch> branches;

    @Id
    @GeneratedValue
    @Column(name="COMPANY_ID")
    public int getCompanyId() {
        return companyId;
    }

    public void setCompanyId(int companyId) {
        this.companyId = companyId;
    }

    @Column(name="COMPANY_NAME")
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    @OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="company")
    public List<Branch> getBranches() {
        return branches;
    }

    public void setBranches(List<Branch> branches) {
        this.branches = branches;
    }


}

child class, Branch

@Entity
public class Branch {

    private int branchId;
    private String branchName;
    private Company company;

    @Id
    @GeneratedValue
    @Column(name="BRANCH_ID")
    public int getBranchId() {
        return branchId;
    }

    public void setBranchId(int branchId) {
        this.branchId = branchId;
    }

    @Column(name="BRANCH_NAME")
    public String getBranchName() {
        return branchName;
    }

    public void setBranchName(String branchName) {
        this.branchName = branchName;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="COMPANY_ID")
    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }


}

Why is &#65279; appearing in my HTML?

If you are using Notepad++, "Menu" >> "Encoding" >> "Convert to UTF-8" your "include" files.

How to autosize and right-align GridViewColumn data in WPF?

If your listview is also re-sizing then you can use a behavior pattern to re-size the columns to fit the full ListView width. Almost the same as you using grid.column definitions

<ListView HorizontalAlignment="Stretch"
          Behaviours:GridViewColumnResize.Enabled="True">
        <ListViewItem></ListViewItem>
        <ListView.View>
            <GridView>
                <GridViewColumn  Header="Column *"
                                   Behaviours:GridViewColumnResize.Width="*" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox HorizontalAlignment="Stretch" Text="Example1" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>

See the following link for some examples and link to source code http://lazycowprojects.tumblr.com/post/7063214400/wpf-c-listview-column-width-auto

Is Android using NTP to sync time?

i wanted to ask if Android Devices uses the network time protocol (ntp) to synchronize the time.

For general time synchronization, devices with telephony capability, where the wireless provider provides NITZ information, will use NITZ. My understanding is that NTP is used in other circumstances: NITZ-free wireless providers, WiFi-only, etc.

Your cited blog post suggests another circumstance: on-demand time synchronization in support of GPS. That is certainly conceivable, though I do not know whether it is used or not.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

Actually I took a closer look at the user table in mysql database, turns out someone prior to me edited the ssl_type field for user root to SSL.

I edited that field and restarted mysql and it worked like a charm.

Thanks.

Transparent background on winforms?

A simple solution to get a transparent background in a windows form is to overwrite the OnPaintBackground method like this:

protected override void OnPaintBackground(PaintEventArgs e)
{
    //empty implementation
}

(Notice that the base.OnpaintBackground(e) is removed from the function)

Blue and Purple Default links, how to remove?

If you wants display anchors in your own choice of colors than you should define the color in anchor tag property in CSS like this:-

a { text-decoration: none; color:red; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: none; }

see the demo:- http://jsfiddle.net/zSWbD/7/

Detect if device is iOS

You can also use includes

  const isApple = ['iPhone', 'iPad', 'iPod', 'iPad Simulator', 'iPhone Simulator', 'iPod Simulator',].includes(navigator.platform)

How to downgrade Node version

 curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
 sudo npm install -g n
 sudo n 10.15
 npm install
 npm audit fix
 npm start

How to print object array in JavaScript?

Emm... Why not to use something like this?

_x000D_
_x000D_
function displayArrayObjects(arrayObjects) {_x000D_
        var len = arrayObjects.length, text = "";_x000D_
_x000D_
        for (var i = 0; i < len; i++) {_x000D_
            var myObject = arrayObjects[i];_x000D_
            _x000D_
            for (var x in myObject) {_x000D_
                text += ( x + ": " + myObject[x] + " ");_x000D_
            }_x000D_
            text += "<br/>";_x000D_
        }_x000D_
_x000D_
        document.getElementById("message").innerHTML = text;_x000D_
    }_x000D_
            _x000D_
            _x000D_
            var lineChartData = [{_x000D_
                date: new Date(2009, 10, 2),_x000D_
                value: 5_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 25),_x000D_
                value: 30_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 26),_x000D_
                value: 72,_x000D_
                customBullet: "images/redstar.png"_x000D_
            }];_x000D_
_x000D_
            displayArrayObjects(lineChartData);
_x000D_
<h4 id="message"></h4>
_x000D_
_x000D_
_x000D_

result:

date: Mon Nov 02 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 5 
date: Wed Nov 25 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 30 
date: Thu Nov 26 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 72 customBullet: images/redstar.png 

jsfiddle

Where does Console.WriteLine go in ASP.NET?

Mac, In Debug mode there is a tab for the Output. enter image description here

Prevent Android activity dialog from closing on outside touch

I use this in onCreate(), seems to work on any version of Android; tested on 5.0 and 4.4.x, can't test on Gingerbread, Samsung devices (Note 1 running GB) have it this way by default:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    {
        setFinishOnTouchOutside(false);
    }
    else
    {
        getWindow().clearFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
    }

    super.onCreate(savedInstanceState);

Getting all names in an enum as a String[]

Something like this would do:

public static String[] names() {
  String[] names = new String[values().length];
  int index = 0;

  for (State state : values()) {
    names[index++] = state.name();
  }

  return names;
}

The documentation recommends using toString() instead of name() in most cases, but you have explicitly asked for the name here.

How to set a Header field on POST a form?

Set a cookie value on the page, and then read it back server side.

You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.

ansible : how to pass multiple commands

Here is worker like this. \o/

- name: "Exec items"
  shell: "{{ item }}"
  with_items:
    - echo "hello"
    - echo "hello2"

sudo echo "something" >> /etc/privilegedFile doesn't work

Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

How to do URL decoding in Java?

This has been answered before (although this question was first!):

"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."

As URL class documentation states:

The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().

The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.

Basically:

String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());

will give you:

https://mywebsite/docs/english/site/mybook.do?request_type

Ruby on Rails: how to render a string as HTML?

You are mixing your business logic with your content. Instead, I'd recommend sending the data to your page and then using something like JQuery to place the data where you need it to go.

This has the advantage of keeping all your HTML in the HTML pages where it belongs so your web designers can modify the HTML later without having to pour through server side code.

Or if you're not wanting to use JavaScript, you could try this:

@str = "Hi"

<b><%= @str ></b>

At least this way your HTML is in the HTML page where it belongs.

Get the index of the object inside an array, matching a condition

var list =  [
                {prop1:"abc",prop2:"qwe"},
                {prop1:"bnmb",prop2:"yutu"},
                {prop1:"zxvz",prop2:"qwrq"}
            ];

var findProp = p => {
    var index = -1;
    $.each(list, (i, o) => {
        if(o.prop2 == p) {
            index = i;
            return false; // break
        }
    });
    return index; // -1 == not found, else == index
}

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

There's a bit of confusion in your question:

  • a Date datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE into a Date.
  • When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the TO_CHAR function. In Oracle, a Date has no format: it is a point in time.
  • Reciprocally, you would use TO_TIMESTAMP_TZ to convert a VARCHAR2 to a TIMESTAMP, but this won't convert a Date to a TIMESTAMP.
  • You use FROM_TZ to add the time zone information to a TIMESTAMP (or a Date).
  • In Oracle, CST is a time zone but CDT is not. CDT is a daylight saving information.
  • To complicate things further, CST/CDT (-05:00) and CST/CST (-06:00) will have different values obviously, but the time zone CST will inherit the daylight saving information depending upon the date by default.

So your conversion may not be as simple as it looks.

Assuming that you want to convert a Date d that you know is valid at time zone CST/CST to the equivalent at time zone CST/CDT, you would use:

SQL> SELECT from_tz(d, '-06:00') initial_ts,
  2         from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
  3    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  4                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  5            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00

My default timestamp format has been used here. I can specify a format explicitely:

SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
  2         to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
  3                 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
  4    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  5                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  6            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00      2012-10-09 02:10:21 -05:00

Store text file content line by line into array

You can use this code. This works very fast!

public String[] loadFileToArray(String fileName) throws IOException {
    String s = new String(Files.readAllBytes(Paths.get(fileName)));
    return Arrays.stream(s.split("\n")).toArray(String[]::new);
}

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

You can use this methode to check if a view has children or not .

public static boolean hasChildren(ViewGroup viewGroup) {
    return viewGroup.getChildCount() > 0;
 }

How to decrypt a password from SQL server?

A quick google indicates that pwdencrypt() is not deterministic, and your statement select pwdencrypt('AAAA') returns a different value on my installation!

See also this article http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:

public List<Book> list() {
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from book").list();
    return list;
}

The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.

public List<Book> list() {                                                                               
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from Book").list();
    return list;
}

Get all parameters from JSP page

This should print out all Parameters that start with "Question".

<html><body>
<%@ page import = "java.util.*" %>
<b>Parameters:</b><br>
<%
  Enumeration parameterList = request.getParameterNames();
  while( parameterList.hasMoreElements() )
  {
    String sName = parameterList.nextElement().toString();
    if(sName.toLowerCase.startsWith("question")){
      String[] sMultiple = request.getParameterValues( sName );
      if( 1 >= sMultiple.length )
        // parameter has a single value. print it.
        out.println( sName + " = " + request.getParameter( sName ) + "<br>" );
      else
        for( int i=0; i<sMultiple.length; i++ )
          // if a paramater contains multiple values, print all of them
          out.println( sName + "[" + i + "] = " + sMultiple[i] + "<br>" );
    }
  }
%>
</body></html>

In Typescript, How to check if a string is Numeric

The way to convert a string to a number is with Number, not parseFloat.

Number('1234') // 1234
Number('9BX9') // NaN

You can also use the unary plus operator if you like shorthand:

+'1234' // 1234
+'9BX9' // NaN

Be careful when checking against NaN (the operator === and !== don't work as expected with NaN). Use:

 isNaN(+maybeNumber) // returns true if NaN, otherwise false

Docker compose, running containers in net:host

you can try just add

network_mode: "host"

example :

version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"

list option available

network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"

https://docs.docker.com/compose/compose-file/#network_mode

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Honestly I didnt bother to deal with the grants and this worked even without the privileges:

echo "select * from employee" | mysql --host=HOST --port=PORT --user=UserName --password=Password DATABASE.SCHEMA > output.txt

WPF ListView - detect when selected item is clicked

You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.

XAML:

<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...

Code behind:

private void listView_Click(object sender, RoutedEventArgs e)
{
    var item = (sender as ListView).SelectedItem;
    if (item != null)
    {
        ...
    }
}

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

How can I export data to an Excel file

You can use ExcelDataReader to read existing Excel file:

using (var stream = File.Open("C:\\temp\\input.xlsx", FileMode.Open, FileAccess.Read))
{
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        while (reader.Read())
        {
            for (var i = 0; i < reader.FieldCount; i++)
            {
                var value = reader.GetValue(i)?.ToString();
            }
        }
    }
}

After you collected all data needed you can try my SwiftExcel library to export it to the new Excel file:

using (var ew = new ExcelWriter("C:\\temp\\output.xlsx"))
{
    for (var i = 1; i < 10; i++)
    {
        ew.Write("your_data", i, 1);
    }
}

Nuget commands to install both libraries:

Install-Package ExcelDataReader

Install-Package SwiftExcel

Simple URL GET/POST function in Python

import urllib

def fetch_thing(url, params, method):
    params = urllib.urlencode(params)
    if method=='POST':
        f = urllib.urlopen(url, params)
    else:
        f = urllib.urlopen(url+'?'+params)
    return (f.read(), f.code)


content, response_code = fetch_thing(
                              'http://google.com/', 
                              {'spam': 1, 'eggs': 2, 'bacon': 0}, 
                              'GET'
                         )

[Update]

Some of these answers are old. Today I would use the requests module like the answer by robaple.

Export DataBase with MySQL Workbench with INSERT statements

In MySQL Workbench 6.1.

I had to click on the Apply changes button in the insertion panel (only once, because twice and MWB crashes...).

You have to do it for each of your table.

Apply changes button

Then export your schema :

Export schema

Check Generate INSERT statements for table

Check INSERT

It is okay !

Inserts ok

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'] will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _, is that a typo?

How to round the corners of a button

An alternative answer which sets a border too (making it more like a button) is here ... How to set rectangle border for custom type UIButton

Google Chromecast sender error if Chromecast extension is not installed or using incognito

By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.

Does Python have “private” variables in classes?

Python does not have any private variables like C++ or Java does. You could access any member variable at any time if wanted, too. However, you don't need private variables in Python, because in Python it is not bad to expose your classes member variables. If you have the need to encapsulate a member variable, you can do this by using "@property" later on without breaking existing client code.

In python the single underscore "_" is used to indicate, that a method or variable is not considered as part of the public api of a class and that this part of the api could change between different versions. You can use these methods/variables, but your code could break, if you use a newer version of this class.

The double underscore "__" does not mean a "private variable". You use it to define variables which are "class local" and which can not be easily overidden by subclasses. It mangles the variables name.

For example:

class A(object):
    def __init__(self):
        self.__foobar = None # will be automatically mangled to self._A__foobar

class B(A):
    def __init__(self):
        self.__foobar = 1 # will be automatically mangled to self._B__foobar

self.__foobar's name is automatically mangled to self._A__foobar in class A. In class B it is mangled to self._B__foobar. So every subclass can define its own variable __foobar without overriding its parents variable(s). But nothing prevents you from accessing variables beginning with double underscores. However, name-mangling prevents you from calling this variables /methods incidentally.

I strongly recommend to watch Raymond Hettingers talk "Pythons class development toolkit" from Pycon 2013 (should be available on Youtube), which gives a good example why and how you should use @property and "__"-instance variables.

If you have exposed public variables and you have the need to encapsulate them, then you can use @property. Therefore you can start with the simplest solution possible. You can leave member variables public unless you have a concrete reason to not do so. Here is an example:

class Distance:
    def __init__(self, meter):
        self.meter = meter


d = Distance(1.0)
print(d.meter)
# prints 1.0

class Distance:
    def __init__(self, meter):
        # Customer request: Distances must be stored in millimeters.
        # Public available internals must be changed.
        # This would break client code in C++.
        # This is why you never expose public variables in C++ or Java.
        # However, this is python.
        self.millimeter = meter * 1000

    # In python we have @property to the rescue.
    @property
    def meter(self):
        return self.millimeter *0.001

    @meter.setter
    def meter(self, value):
        self.millimeter = meter * 1000

d = Distance(1.0)
print(d.meter)
# prints 1.0

/usr/bin/codesign failed with exit code 1

I had the exact same error, and tried everything under the sun, including what was elsewhere on this page, with no success. What the problem was for me was that in Keychain Access, the actual Apple WWDR certificate was marked as "Always Trust". It needed to be "System Defaults". That goes for your Development and Distribution certificates, too. If any of them are incorrectly set to "Always Trust", that can apparently cause this problem.

So, in Keychain Access, click on the Apple Worldwide Developer Relations Certificate Authority certificate, select Get Info. Then, expand the Trust settings, and for the combo box for "When using this certificate:", choose "System Defaults".

Others have commented that you may have to do this in System and login keychains for these errors.

How do I print the key-value pairs of a dictionary in python

for key, value in d.iteritems():
    print key, '\t', value

Where can I find decent visio templates/diagrams for software architecture?

For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.

I use the Visio Network and Database stencils to model most other requirements.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I just had this problem, and the cause seemed to be that a directory had been flagged as in conflict. To fix:

svn update
svn resolved <the directory in conflict>
svn commit

How do I adb pull ALL files of a folder present in SD Card

Yep, just use the trailing slash to recursively pull the directory. Works for me with Nexus 5 and current version of adb (March 2014).

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32. This leads to a broken array with wrong dimensions and the above mentioned error.

To solve the problem, make sure that all images have the correct dimensions.

What does the "$" sign mean in jQuery or JavaScript?

The $ is just a function. It is actually an alias for the function called jQuery, so your code can be written like this with the exact same results:

jQuery('#Text').click(function () {
  jQuery('#Text').css('color', 'red');
});

Logcat not displaying my log calls

Please go to Task Manager and kill the adb.exe process. Restart your eclipse again.

or

try adb kill-server and then adb start-server command.

How to fill Dataset with multiple tables?

public DataSet GetDataSet()
    {
        try
        {
            DataSet dsReturn = new DataSet();
            using (SqlConnection myConnection = new SqlConnection(Core.con))
            {
                string query = "select * from table1;  select* from table2";
                SqlCommand cmd = new SqlCommand(query, myConnection);
                myConnection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                dsReturn.Load(reader, LoadOption.PreserveChanges, new string[] { "tableOne", "tableTwo" });
                return dsReturn;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

Why is a ConcurrentModificationException thrown and how to debug it

Try using a ConcurrentHashMap instead of a plain HashMap

Progress during large file copy (Copy-Item & Write-Progress?)

It seems like a much better solution to just use BitsTransfer, it seems to come OOTB on most Windows machines with PowerShell 2.0 or greater.

Import-Module BitsTransfer
Start-BitsTransfer -Source $Source -Destination $Destination -Description "Backup" -DisplayName "Backup"

Make index.html default, but allow index.php to be visited if typed in

I agree with @TheAlpha's accepted answer, Apache reads the DirectoryIndex target files from left to right , if the first file exists ,apche serves it and if it doesnt then the next file is served as an index for the directory. So if you have the following Directive :

DirectoryIndex file1.html file2.html

Apache will serve /file.html as index ,You will need to change the order of files if you want to set /file2.html as index

DirectoryIndex file2.html file1.html

You can also set index file using a RewriteRule

RewriteEngine on

RewriteRule ^$ /index.html [L]

RewriteRule above will rewrite your homepage to /index.html the rewriting happens internally so http://example.com/ would show you the contents ofindex.html .

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

How to convert comma separated string into numeric array in javascript

You can split and convert like

 var strVale = "130,235,342,124 ";
 var intValArray=strVale.split(',');
 for(var i=0;i<intValArray.length;i++{
     intValArray[i]=parseInt(intValArray[i]);
}

Now you can use intValArray in you logic.

Sort divs in jQuery based on attribute 'data-sort'?

Use this function

   var result = $('div').sort(function (a, b) {

      var contentA =parseInt( $(a).data('sort'));
      var contentB =parseInt( $(b).data('sort'));
      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
   });

   $('#mylist').html(result);

You can call this function just after adding new divs.

If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:

$(targetSelector).sort(function (a, b) {
    // ...
}).appendTo($container);

Fetch frame count with ffmpeg

Note: The presence of an edit list in MP4/M4V/M4A/MOV can affect your frame number. See Edit lists below.


ffprobe: Query the container

ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 input.mp4
  • This is a fast method.
  • Not all formats (such as Matroska) will report the number of frames resulting in the output of N/A. See the other methods listed below.

ffprobe: Count the number of frames

ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of default=nokey=1:noprint_wrappers=1 input.mkv
  • This is a slow method.
  • Add the -skip_frame nokey option to only count key frames.

ffmpeg: Count the number of frames

If you do not have ffprobe you can use ffmpeg instead:

ffmpeg -i input.mkv -map 0:v:0 -c copy -f null -
  • This is a somewhat fast method.
  • Refer to frame= near the end of the console output.
  • Add the -discard nokey input option (before -i) to only count key frames.

Edit lists

Ignore the MP4/M4V/M4A/MOV edit list with the -ignore_editlist 1 input option. Default is to not ignore the edit list.

What the ffprobe options mean

  • -v error This hides "info" output (version info, etc) which makes parsing easier.

  • -count_frames Count the number of frames per stream and report it in the corresponding stream section.

  • -select_streams v:0 Select only the video stream.

  • -show_entries stream=nb_frames or -show_entries stream=nb_read_frames Show only the entry for nb_frames or nb_read_frames.

  • -of default=nokey=1:noprint_wrappers=1 Set output format (aka the "writer") to default, do not print the key of each field (nokey=1), and do not print the section header and footer (noprint_wrappers=1). There are shorter alternatives such as -of csv=p=0.

Also see


mediainfo

The well known mediainfo tool can output the number of frames:

mediainfo --Output="Video;%FrameCount%" input.avi

MP4Box

For MP4/M4V/M4A files.

MP4Box from gpac can show the number of frames:

MP4Box -info input.mp4

Refer to the Media Info line in the output for the video stream in question:

Media Info: Language "Undetermined (und)" - Type "vide:avc1" - 2525 samples

In this example the video stream has 2525 frames.


boxdumper

For MP4/M4V/M4A/MOV files.

boxdumper is a simple tool from l-smash. It will output a large amount of information. Under the stsz sample size box section refer to sample_count for the number of frames. In this example the input has 1900 video frames:

boxdumper input.mp4
  ...
  [stsz: Sample Size Box]
    position = 342641
    size = 7620
    version = 0
    flags = 0x000000
    sample_size = 0 (variable)
    sample_count = 1900
  • Be aware that a file may have more than one stsz atom.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

Remove last character from string. Swift language

The dropLast() function removes the last element of the string.

var expression = "45+22"
expression = expression.dropLast()

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

include and require functions require file path, but you are giving file URI instead. The parameter should not be the one that includes http/https.

Your code should be something like:

include ("folder/file.php");

Execute SQL script from command line

Take a look at the sqlcmd utility. It allows you to execute SQL from the command line.

http://msdn.microsoft.com/en-us/library/ms162773.aspx

It's all in there in the documentation, but the syntax should look something like this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName 
    -Q "DROP TABLE MyTable"

Android Studio suddenly cannot resolve symbols

try to change your build.gradle with these value:

android { compileSdkVersion 18 buildToolsVersion '21.0.1'

defaultConfig {
    minSdkVersion 18
    targetSdkVersion 18
}

How to center div vertically inside of absolutely positioned parent div

You can do it by using display:table; in parent div and display: table-cell; vertical-align: middle; in child div

_x000D_
_x000D_
<div style="display:table;">_x000D_
      <div style="text-align: left;  height: 56px;  background-color: pink; display: table-cell; vertical-align: middle;">_x000D_
          <div style="background-color: lightblue; ">test</div>_x000D_
      </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to trap the backspace key using jQuery?

Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .

$('html').on('keydown' , function(event) {

        if(! $(event.target).is('input')) {
            console.log(event.which);
           //event.preventDefault();
           if(event.which == 8) {
            //  alert('backspace pressed');
            return false;
         }
        }
});

returning false => both event.preventDefault and event.stopPropagation are in effect .

vba pass a group of cells as range to function

As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.

So as on the above question I have putted my basic efforts.

Function multi_add(a As Range, ParamArray b() As Variant) As Double

    Dim ele As Variant

    Dim i As Long

    For Each ele In a
        multi_add = a + ele.Value **- a**
    Next ele

    For i = LBound(b) To UBound(b)
        For Each ele In b(i)
            multi_add = multi_add + ele.Value
        Next ele
    Next i

End Function

- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.