Programs & Examples On #Madcap

MySQL equivalent of DECODE function in Oracle

You can use a CASE statement...however why don't you just create a table with an integer for ages between 0 and 150, a varchar for the written out age and then you can just join on that

Access Control Request Headers, is added to header in AJAX request with jQuery

Try to use the rack-cors gem. And add the header field in your Ajax call.

E11000 duplicate key error index in mongodb mongoose

I had the same problem in my project while I social media signup. when the user joins using email first-time work without any issue. when another user signup using email there is an issue due to a null value assigned to the social media id. the reason is only one user should be allowed to insert a null value according to unique true constrain.

Error Schema:

facebookId: {
    type: String,
    index:true
  },

Solution Schema:

  1. Drop the existing index created against facebookId db.users.dropIndex(facebookid_)

2)when we use sparse: true property it allows us to store multiple null values

  facebookId: {
    type: String,
    index:true,
    unique:true,
    sparse:true
  },

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

Check array position for null/empty

If your array is not initialized then it contains randoms values and cannot be checked !

To initialize your array with 0 values:

int array[5] = {0};

Then you can check if the value is 0:

array[4] == 0;

When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.

If you have an array of pointers, better use the nullptr value to check:

char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr

if (array[4] == nullptr)
    // do something

javascript regex : only english letters allowed

The answer that accepts empty string:

/^[a-zA-Z]*$/.test('something')

the * means 0 or more occurrences of the preceding item.

How to check if a value exists in an array in Ruby

Ruby has eleven methods to find elements in an array.

The preferred one is include? or, for repeated access, creat a Set and then call include? or member?.

Here are all of them:

array.include?(element) # preferred method
array.member?(element)
array.to_set.include?(element)
array.to_set.member?(element)
array.index(element) > 0
array.find_index(element) > 0
array.index { |each| each == element } > 0
array.find_index { |each| each == element } > 0
array.any? { |each| each == element }
array.find { |each| each == element } != nil
array.detect { |each| each == element } != nil

They all return a trueish value if the element is present.

include? is the preferred method. It uses a C-language for loop internally that breaks when an element matches the internal rb_equal_opt/rb_equal functions. It cannot get much more efficient unless you create a Set for repeated membership checks.

VALUE
rb_ary_includes(VALUE ary, VALUE item)
{
  long i;
  VALUE e;

  for (i=0; i<RARRAY_LEN(ary); i++) {
    e = RARRAY_AREF(ary, i);
    switch (rb_equal_opt(e, item)) {
      case Qundef:
        if (rb_equal(e, item)) return Qtrue;
        break;
      case Qtrue:
        return Qtrue;
    }
  }
  return Qfalse;
}

member? is not redefined in the Array class and uses an unoptimized implementation from the Enumerable module that literally enumerates through all elements:

static VALUE
member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
{
  struct MEMO *memo = MEMO_CAST(args);

  if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
    MEMO_V2_SET(memo, Qtrue);
    rb_iter_break();
  }
  return Qnil;
}

static VALUE
enum_member(VALUE obj, VALUE val)
{
  struct MEMO *memo = MEMO_NEW(val, Qfalse, 0);

  rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
  return memo->v2;
}

Translated to Ruby code this does about the following:

def member?(value)
  memo = [value, false, 0]
  each_with_object(memo) do |each, memo|
    if each == memo[0]
      memo[1] = true 
      break
    end
  memo[1]
end

Both include? and member? have O(n) time complexity since the both search the array for the first occurrence of the expected value.

We can use a Set to get O(1) access time at the cost of having to create a Hash representation of the array first. If you repeatedly check membership on the same array this initial investment can pay off quickly. Set is not implemented in C but as plain Ruby class, still the O(1) access time of the underlying @hash makes this worthwhile.

Here is the implementation of the Set class:

module Enumerable
  def to_set(klass = Set, *args, &block)
    klass.new(self, *args, &block)
  end
end

class Set
  def initialize(enum = nil, &block) # :yields: o
    @hash ||= Hash.new
    enum.nil? and return
    if block
      do_with_enum(enum) { |o| add(block[o]) }
    else
      merge(enum)
    end
  end

  def merge(enum)
    if enum.instance_of?(self.class)
      @hash.update(enum.instance_variable_get(:@hash))
    else
      do_with_enum(enum) { |o| add(o) }
    end
    self
  end

  def add(o)
    @hash[o] = true
    self
  end

  def include?(o)
    @hash.include?(o)
  end
  alias member? include?

  ...
end

As you can see the Set class just creates an internal @hash instance, maps all objects to true and then checks membership using Hash#include? which is implemented with O(1) access time in the Hash class.

I won't discuss the other seven methods as they are all less efficient.

There are actually even more methods with O(n) complexity beyond the 11 listed above, but I decided to not list them since they scan the entire array rather than breaking at the first match.

Don't use these:

# bad examples
array.grep(element).any? 
array.select { |each| each == element }.size > 0
...

ReactJS SyntheticEvent stopPropagation() only works with React events?

React uses event delegation with a single event listener on document for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation on React's synthetic event is possible because React handles propagation of synthetic events internally.

Working JSFiddle with the fixes from below.

React Stop Propagation on jQuery Event

Use Event.stopImmediatePropagation to prevent your other (jQuery in this case) listeners on the root from being called. It is supported in IE9+ and modern browsers.

stopPropagation: function(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
},
  • Caveat: Listeners are called in the order in which they are bound. React must be initialized before other code (jQuery here) for this to work.

jQuery Stop Propagation on React Event

Your jQuery code uses event delegation as well, which means calling stopPropagation in the handler is not stopping anything; the event has already propagated to document, and React's listener will be triggered.

// Listener bound to `document`, event delegation
$(document).on('click', '.stop-propagation', function(e){
    e.stopPropagation();
});

To prevent propagation beyond the element, the listener must be bound to the element itself:

// Listener bound to `.stop-propagation`, no delegation
$('.stop-propagation').on('click', function(e){
    e.stopPropagation();
});

Edit (2016/01/14): Clarified that delegation is necessarily only used for events that bubble. For more details on event handling, React's source has descriptive comments: ReactBrowserEventEmitter.js.

Add image in pdf using jspdf

For result in base64, before convert to canvas:

var getBase64ImageUrl = function(url, callback, mine) {

                    var img = new Image();

                    url = url.replace("http://","//");

                    img.setAttribute('crossOrigin', 'anonymous');

                    img.onload = function () {
                        var canvas = document.createElement("canvas");
                        canvas.width =this.width;
                        canvas.height =this.height;

                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(this, 0, 0);

                        var dataURL = canvas.toDataURL(mine || "image/jpeg");

                        callback(dataURL);
                    };
                    img.src = url;

                    img.onerror = function(){

                        console.log('on error')
                        callback('');

                    }

            }

   getBase64ImageUrl('Koala.jpeg', function(img){
         //img is a base64encode result
         //return img;
          console.log(img);

          var doc = new jsPDF();
              doc.setFontSize(40);
              doc.text(30, 20, 'Hello world!');
              doc.output('datauri');
              doc.addImage(img, 'JPEG', 15, 40, 180, 160);
    });

Add two numbers and display result in textbox with Javascript

When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".

How update the _id of one MongoDB Document?

In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):

db.someCollection.find().snapshot().forEach(function(doc) { 
   if (doc._id.indexOf("2019:") != 0) {
       print("Processing: " + doc._id);
       var oldDocId = doc._id;
       doc._id = "2019:" + doc._id; 
       db.someCollection.insert(doc);
       db.someCollection.remove({_id: oldDocId});
   }
});

if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.

Error 5 : Access Denied when starting windows service

check windows event log for detailed error message. I resolved the same after checking event log.

PHP - Check if two arrays are equal

If you want to check non associative arrays, here is the solution:

$a = ['blog', 'company'];
$b = ['company', 'blog'];

(count(array_unique(array_merge($a, $b))) === count($a)) ? 'Equals' : 'Not Equals';
// Equals

Username and password in command for git push

For anyone having issues with passwords with special chars just omit the password and it will prompt you for it:

git push https://[email protected]/YOUR_GIT_USERNAME/yourGitFileName.git

Modulo operator in Python

In addition to the other answers, the fmod documentation has some interesting things to say on the subject:

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

Vertical Menu in Bootstrap

Responsive utility classes

Easiest way I can think of is to have a vertical left menu AND the collapsing Top Nav in your design and attach/use bootstraps responsive css.

Then just add classes of hidden phone, tablet etc (to suit) to your left nav and hidden desktop etc to the top nav

see: http://twitter.github.com/bootstrap/scaffolding.html#responsive

play around with that and hopefully it should be able to do what you want

How to change Status Bar text color in iOS

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }
}

Java JDBC - How to connect to Oracle using Service Name instead of SID

In case you are using eclipse to connect oracle without SID. There are two drivers to select i.e., Oracle thin driver and other is other driver. Select other drivers and enter service name in database column. Now you can connect directly using service name without SID.

Uncaught TypeError: Cannot set property 'onclick' of null

"blue_box" is null -- are you positive whatever it is with "id='blue'" exists when this is being run?

try console.log(document.getElementById("blue")) in chrome or FF with firebug. Your script might be running before the 'blue' element is loaded. In this case, you'll need to add the event after the page has loaded (window.onload).

How to generate a simple popup using jQuery

Simple popup window by using html5 and javascript.

html:-

    <dialog id="window">  
     <h3>Sample Dialog!</h3>  
     <p>Lorem ipsum dolor sit amet</p>  
     <button id="exit">Close Dialog</button>
    </dialog>  

  <button id="show">Show Dialog</button> 

JavaScript:-

   (function() {  

            var dialog = document.getElementById('window');  
            document.getElementById('show').onclick = function() {  
                dialog.show();  
            };  
            document.getElementById('exit').onclick = function() {  
                dialog.close();  
            };
        })();

How to take the nth digit of a number in python

Ok, first of all, use the str() function in python to turn 'number' into a string

number = 9876543210 #declaring and assigning
number = str(number) #converting

Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number

print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'

if you like it in the short form

print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'

How do I create a link using javascript?

<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

How do you remove a specific revision in the git history?

Here is a way to remove non-interactively a specific <commit-id>, knowing only the <commit-id> you would like to remove:

git rebase --onto <commit-id>^ <commit-id> HEAD

failed to find target with hash string android-23

It worked for me by changing compileSdkVersion to 24 and targetSdkVersion to 24 and change compile to com.android.support:appcompat-v7:24.1.0

Determine the data types of a data frame's columns

Simply pass your data frame into the following function:

data_types <- function(frame) {
  res <- lapply(frame, class)
  res_frame <- data.frame(unlist(res))
  barplot(table(res_frame), main="Data Types", col="steelblue", ylab="Number of Features")
}

to produce a plot of all data types in your data frame. For the iris dataset we get the following:

data_types(iris)

enter image description here

git - Your branch is ahead of 'origin/master' by 1 commit

I resolved this by just running a simple:

git pull

Nothing more. Now it's showing:

# On branch master
nothing to commit, working directory clean

Make a Bash alias that takes a parameter?

You don't have to do anything, alias does this automatically.

For example, if i want to make git pull origin master parameterized, i can simply create an alias as follows:

alias gpull = 'git pull origin '

and when actually calling it, you can pass 'master' (the branch name) as a parameter, like this:

gpull master
//or any other branch
gpull mybranch

How can I get query parameters from a URL in Vue.js?

As of this date, the correct way according to the dynamic routing docs is:

this.$route.params.yourProperty

instead of

this.$route.query.yourProperty

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

How to add text inside the doughnut chart using Chart.js?

I'd avoid modifying the chart.js code to accomplish this, since it's pretty easy with regular CSS and HTML. Here's my solution:

HTML:

<canvas id="productChart1" width="170"></canvas>
<div class="donut-inner">
    <h5>47 / 60 st</h5>
    <span>(30 / 25 st)</span>
</div>

CSS:

.donut-inner {
   margin-top: -100px;
   margin-bottom: 100px;
}
.donut-inner h5 {
   margin-bottom: 5px;
   margin-top: 0;
}
.donut-inner span {
   font-size: 12px;
}

The output looks like this:

enter image description here

Add element to a JSON file?

You can do this.

data[0]['f'] = var

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

jQuery and TinyMCE: textarea value doesn't submit

I had this problem for a while and triggerSave() didn't work, nor did any of the other methods.

So I found a way that worked for me ( I'm adding this here because other people may have already tried triggerSave and etc... ):

tinyMCE.init({
   selector: '.tinymce', // This is my <textarea> class
   setup : function(ed) {
                  ed.on('change', function(e) {
                     // This will print out all your content in the tinyMce box
                     console.log('the content '+ed.getContent());
                     // Your text from the tinyMce box will now be passed to your  text area ... 
                     $(".tinymce").text(ed.getContent()); 
                  });
            }
   ... Your other tinyMce settings ...
});

When you're submitting your form or whatever all you have to do is grab the data from your selector ( In my case: .tinymce ) using $('.tinymce').text().

How do you tell if a string contains another string in POSIX sh?

Pure POSIX shell:

#!/bin/sh
CURRENT_DIR=`pwd`

case "$CURRENT_DIR" in
  *String1*) echo "String1 present" ;;
  *String2*) echo "String2 present" ;;
  *)         echo "else" ;;
esac

Extended shells like ksh or bash have fancy matching mechanisms, but the old-style case is surprisingly powerful.

Get month name from Date

_x000D_
_x000D_
document.write(new Date().toLocaleString('en-us',{month:'long', year:'numeric', day:'numeric'}))
_x000D_
_x000D_
_x000D_

CSS strikethrough different color from text?

Assigning the desired line-through color to a parent element works for the deleted text element (<del>) as well - making the assumption the client renders <del> as a line-through.

http://jsfiddle.net/kpowz/vn9RC/

Getting Keyboard Input

In java we can read input values in 6 ways:

  1. Scanner Class
  2. BufferedReader
  3. Console class
  4. Command line
  5. AWT, String, GUI
  6. System properties
  1. Scanner class: present in java.util.*; package and it has many methods, based your input types you can utilize those methods. a. nextInt() b. nextLong() c. nextFloat() d. nextDouble() e. next() f. nextLine(); etc...
import java.util.Scanner;
public class MyClass {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a :");
        int a = sc.nextInt();
        System.out.println("Enter b :");
        int b = sc.nextInt();
        
        int c = a + b;
        System.out.println("Result: "+c);
    }
}
  1. BufferedReader class: present in java.io.*; package & it has many method, to read the value from the keyboard use "readLine()" : this method reading one line at a time.
import java.io.BufferedReader;
import java.io.*;
public class MyClass {
    public static void main(String args[]) throws IOException {
       BufferedReader br = new BufferedReader(new BufferedReader(new InputStreamReader(System.in)));
        System.out.println("Enter a :");
        int a = Integer.parseInt(br.readLine());
        System.out.println("Enter b :");
        int b = Integer.parseInt(br.readLine());
        
        int c = a + b;
        System.out.println("Result: "+c);
    }
}

How to correctly represent a whitespace character

The WhiteSpace CHAR can be referenced using ASCII Codes here. And Character# 32 represents a white space, Therefore:

char space = (char)32;

For example, you can use this approach to produce desired number of white spaces anywhere you want:

int _length = {desired number of white spaces}
string.Empty.PadRight(_length, (char)32));

WebAPI to Return XML

Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage( so that I get a return compatible with IHttpActionResult:

return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
       {
           Content = new ObjectContent<SomeType>(objectToSerialize, 
              new System.Net.Http.Formatting.XmlMediaTypeFormatter { 
                  UseXmlSerializer = true 
              })
       });

How can I create a copy of an Oracle table without copying the data?

Simply write a query like:

create table new_table as select * from old_table where 1=2;

where new_table is the name of the new table that you want to create and old_table is the name of the existing table whose structure you want to copy, this will copy only structure.

Datetime in where clause

select * from tblErrorLog
where errorDate BETWEEN '12/20/2008' AND DATEADD(DAY, 1, '12/20/2008')

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Can a relative sitemap url be used in a robots.txt?

Good technical & logical question my dear friend. No in robots.txt file you can't go with relative URL of the sitemap; you need to go with the complete URL of the sitemap.

It's better to go with "sitemap: https://www.example.com/sitemap_index.xml"

In the above URL after the colon gives space. I also like to support Deepak.

How do I create a GUI for a windows application using C++?

For such a simple application even MFC would be overkill. If don't want to introduce another dependency just do it in plain vanilla Win32. It will be easier for you if you have never used MFC.

Check out the classic "Programming Windows" by Charles Petzold or some online tutorial (e.g. http://www.winprog.org/tutorial/) and you are ready to go.

apc vs eaccelerator vs xcache

Check out benchmarks and comparisons:

here and here and there

Run PHP Task Asynchronously

It's a great idea to use cURL as suggested by rojoca.

Here is an example. You can monitor text.txt while the script is running in background:

<?php

function doCurl($begin)
{
    echo "Do curl<br />\n";
    $url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $url = preg_replace('/\?.*/', '', $url);
    $url .= '?begin='.$begin;
    echo 'URL: '.$url.'<br>';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    echo 'Result: '.$result.'<br>';
    curl_close($ch);
}


if (empty($_GET['begin'])) {
    doCurl(1);
}
else {
    while (ob_get_level())
        ob_end_clean();
    header('Connection: close');
    ignore_user_abort();
    ob_start();
    echo 'Connection Closed';
    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush();
    flush();

    $begin = $_GET['begin'];
    $fp = fopen("text.txt", "w");
    fprintf($fp, "begin: %d\n", $begin);
    for ($i = 0; $i < 15; $i++) {
        sleep(1);
        fprintf($fp, "i: %d\n", $i);
    }
    fclose($fp);
    if ($begin < 10)
        doCurl($begin + 1);
}

?>

Copy data from one existing row to another existing row in SQL?

Use SELECT to Insert records

INSERT tracking (userID, courseID, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent) 
SELECT userID, 11, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent
FROM tracking WHERE courseID = 6 AND course_date > '08-01-2008'

Vim clear last search highlighting

Remapped to in my .vimrc.local file, quick and dirty but very functional:

" Clear last search highlighting
map <Space> :noh<cr>

How do I replace whitespaces with underscore?

use string's replace method:

"this should be connected".replace(" ", "_")

"this_should_be_disconnected".replace("_", " ")

What does the Excel range.Rows property really do?

Range.Rows, Range.Columns and Range.Cells are Excel.Range objects, according to the VBA Type() functions:

?TypeName(Selection.rows)
Range
However, that's not the whole story: those returned objects are extended types that inherit every property and method from Excel::Range - but .Columns and .Rows have a special For... Each iterator, and a special .Count property that aren't quite the same as the parent Range object's iterator and count.

So .Cells is iterated and counted as a collection of single-cell ranges, just like the default iterator of the parent range.

But .Columns is iterated and counted as a collection of vertical subranges, each of them a single column wide;

...And .Rows is iterated and counted as a collection of horizontal subranges, each of them a single row high.

The easiest way to understand this is to step through this code and watch what's selected:

Public Sub Test() 
Dim SubRange As Range Dim ParentRange As Range
Set ParentRange = ActiveSheet.Range("B2:E5")

For Each SubRange In ParentRange.Cells SubRange.Select Next
For Each SubRange In ParentRange.Rows SubRange.Select Next
For Each SubRange In ParentRange.Columns SubRange.Select Next
For Each SubRange In ParentRange SubRange.Select Next
End Sub
Enjoy. And try it with a couple of merged cells in there, just to see how odd merged ranges can be.

How to post data using HttpClient?

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

Maven with Eclipse Juno

This is what I was getting when tried to install m2e from Eclipse Market place. I am using Eclipse Juno.

Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) To: org.eclipse.m2e.core [1.5.0.20140606-0033]

However, the below links is perfect, it works for me.

http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-juno-0

Regards, Bilal

How to use EOF to run through a text file in C?

One possible C loop would be:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}

For now, I would ignore feof and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.

Pitfall to avoid: using char for the type of c. getchar returns the next character cast to an unsigned char and then to an int. This means that on most [sane] platforms the value of EOF and valid "char" values in c don't overlap so you won't ever accidentally detect EOF for a 'normal' char.

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

How do I get the information from a meta tag with JavaScript?

Way - [ 1 ]

function getMetaContent(property, name){
    return document.head.querySelector("["+property+"="+name+"]").content;
}
console.log(getMetaContent('name', 'csrf-token'));

You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 2 ]

function getMetaContent(name){
    return document.getElementsByTagName('meta')[name].getAttribute("content");
}
console.log(getMetaContent('csrf-token'));

You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 3 ]

function getMetaContent(name){
    name = document.getElementsByTagName('meta')[name];
    if(name != undefined){
        name = name.getAttribute("content");
        if(name != undefined){
            return name;
        }
    }
    return null;
}
console.log(getMetaContent('csrf-token'));

Instead getting error, you get null, that is good.

How to find memory leak in a C++ code/project?

Instructions

Things You'll Need

  • Proficiency in C++
  • C++ compiler
  • Debugger and other investigative software tools

1

Understand the operator basics. The C++ operator new allocates heap memory. The delete operator frees heap memory. For every new, you should use a delete so that you free the same memory you allocated:

char* str = new char [30]; // Allocate 30 bytes to house a string.

delete [] str; // Clear those 30 bytes and make str point nowhere.

2

Reallocate memory only if you've deleted. In the code below, str acquires a new address with the second allocation. The first address is lost irretrievably, and so are the 30 bytes that it pointed to. Now they're impossible to free, and you have a memory leak:

char* str = new char [30]; // Give str a memory address.

// delete [] str; // Remove the first comment marking in this line to correct.

str = new char [60]; /* Give str another memory address with
                                                    the first one gone forever.*/

delete [] str; // This deletes the 60 bytes, not just the first 30.

3

Watch those pointer assignments. Every dynamic variable (allocated memory on the heap) needs to be associated with a pointer. When a dynamic variable becomes disassociated from its pointer(s), it becomes impossible to erase. Again, this results in a memory leak:

char* str1 = new char [30];

char* str2 = new char [40];

strcpy(str1, "Memory leak");

str2 = str1; // Bad! Now the 40 bytes are impossible to free.

delete [] str2; // This deletes the 30 bytes.

delete [] str1; // Possible access violation. What a disaster!

4

Be careful with local pointers. A pointer you declare in a function is allocated on the stack, but the dynamic variable it points to is allocated on the heap. If you don't delete it, it will persist after the program exits from the function:

void Leak(int x){

char* p = new char [x];

// delete [] p; // Remove the first comment marking to correct.

}

5

Pay attention to the square braces after "delete." Use delete by itself to free a single object. Use delete [] with square brackets to free a heap array. Don't do something like this:

char* one = new char;

delete [] one; // Wrong

char* many = new char [30];

delete many; // Wrong!

6

If the leak yet allowed - I'm usually seeking it with deleaker (check it here: http://deleaker.com).

Escape text for HTML

.NET 4.0 and above:

using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

If you want an empty string default then a preferred way is one of these (depending on your need):

$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);

If the url parameter something doesn't exist in the url then $_GET['something'] will return null

strval($_GET['something']) -> strval(null) -> ""

and your variable $value is set to an empty string.

  • trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
  • intval() if only numeric values are expected and the default is zero. intval(null) -> 0

Cases to consider:

...&something=value1&key2=value2 (typical)

...&key2=value2 (parameter missing from url $_GET will return null for it)

...&something=+++&key2=value (parameter is " ")

Why this is a preferred approach:

  • It fits neatly on one line and is clear what's going on.
  • It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
  • Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
  • It's compatible with older and newer php.

Update Strict mode may require something like this:

$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);

Questions every good Java/Java EE Developer should be able to answer?

why would you override the toString() method?

Disable mouse scroll wheel zoom on embedded Google Maps

This will give you a responsive Google Map that will stop the scrolling on the iframe, but once clicked on will let you zoom.

Copy and paste this into your html but replace the iframe link with your own. He's an article on it with an example: Disable the mouse scroll wheel zoom on embedded Google Map iframes

<style>
    .overlay {
    background:transparent;
    position:relative;
    width:100%; /* your iframe width */
    height:480px; /* your iframe height */
    top:480px; /* your iframe height */
    margin-top:-480px; /* your iframe height */
    }
</style>
<div class="overlay" onClick="style.pointerEvents='none'"></div>
<iframe src="https://mapsengine.google.com/map/embed?mid=some_map_id" width="100%" height="480"></iframe>

Eclipse does not highlight matching variables

maybe because it not supports code highlights inside scriplets. not sure though.

You can try using one of the eclipse plugin like 'glance search' which works great. Here's a link for that- http://code.google.com/p/eclipse-glance/

batch file to copy files to another location?

robocopy yourfolder yourdestination /MON:0

should do it, although you may need some more options. The switch at the end will re-run robocopy if more than 0 changes are seen.

Convert float to double without losing precision

It's not that you're actually getting extra precision - it's that the float didn't accurately represent the number you were aiming for originally. The double is representing the original float accurately; toString is showing the "extra" data which was already present.

For example (and these numbers aren't right, I'm just making things up) suppose you had:

float f = 0.1F;
double d = f;

Then the value of f might be exactly 0.100000234523. d will have exactly the same value, but when you convert it to a string it will "trust" that it's accurate to a higher precision, so won't round off as early, and you'll see the "extra digits" which were already there, but hidden from you.

When you convert to a string and back, you're ending up with a double value which is closer to the string value than the original float was - but that's only good if you really believe that the string value is what you really wanted.

Are you sure that float/double are the appropriate types to use here instead of BigDecimal? If you're trying to use numbers which have precise decimal values (e.g. money), then BigDecimal is a more appropriate type IMO.

How can I remove an entry in global configuration with git config?

I'm not sure what you mean by "undo" the change. You can remove the core.excludesfile setting like this:

git config --global --unset core.excludesfile

And of course you can simply edit the config file:

git config --global --edit

...and then remove the setting by hand.

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

Updated 5 September 2010

Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:

IE's document.selection.createRange doesn't include leading or trailing blank lines

To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <textarea> or text <input>.

Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's focus() method first.

function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

AngularJS $resource RESTful example

you can just do $scope.todo = Todo.get({ id: 123 }). .get() and .query() on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

That is an HTTP header. You would configure your webserver or webapp to send this header ideally. Perhaps in htaccess or PHP.

Alternatively you might be able to use

<head>...<meta http-equiv="Access-Control-Allow-Origin" content="*">...</head>

I do not know if that would work. Not all HTTP headers can be configured directly in the HTML.

This works as an alternative to many HTTP headers, but see @EricLaw's comment below. This particular header is different.

Caveat

This answer is strictly about how to set headers. I do not know anything about allowing cross domain requests.

About HTTP Headers

Every request and response has headers. The browser sends this to the webserver

GET /index.htm HTTP/1.1

Then the headers

Host: www.example.com
User-Agent: (Browser/OS name and version information)
.. Additional headers indicating supported compression types and content types and other info

Then the server sends a response

Content-type: text/html
Content-length: (number of bytes in file (optional))
Date: (server clock)
Server: (Webserver name and version information)

Additional headers can be configured for example Cache-Control, it all depends on your language (PHP, CGI, Java, htaccess) and webserver (Apache, etc).

How can I symlink a file in Linux?

ln -s sourcepath linkpathname

Note:

-s makes symbolic links instead of hard links

Convert dictionary to bytes and back again python?

If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

For example:

my_dict = {'key' : [1,2,3]}

import json
def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary


def binary_to_dict(the_binary):
    jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
    d = json.loads(jsn)  
    return d

bin = dict_to_binary(my_dict)
print bin

dct = binary_to_dict(bin)
print dct

will give the output

1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101

{u'key': [1, 2, 3]}

Python - Using regex to find multiple matches and print them out

Instead of using re.search use re.findall it will return you all matches in a List. Or you could also use re.finditer (which i like most to use) it will return an Iterator Object and you can just use it to iterate over all found matches.

line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
    print match.group(1)

How to get row from R data.frame

Logical indexing is very R-ish. Try:

 x[ x$A ==5 & x$B==4.25 & x$C==4.5 , ] 

Or:

subset( x, A ==5 & B==4.25 & C==4.5 )

In Git, what is the difference between origin/master vs origin master?

There are actually three things here: origin master is two separate things, and origin/master is one thing. Three things total.

Two branches:

  • master is a local branch
  • origin/master is a remote branch (which is a local copy of the branch named "master" on the remote named "origin")

One remote:

  • origin is a remote

Example: pull in two steps

Since origin/master is a branch, you can merge it. Here's a pull in two steps:

Step one, fetch master from the remote origin. The master branch on origin will be fetched and the local copy will be named origin/master.

git fetch origin master

Then you merge origin/master into master.

git merge origin/master

Then you can push your new changes in master back to origin:

git push origin master

More examples

You can fetch multiple branches by name...

git fetch origin master stable oldstable

You can merge multiple branches...

git merge origin/master hotfix-2275 hotfix-2276 hotfix-2290

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

How to add image that is on my computer to a site in css or html?

If you just want to see the image on your local browser, this can be done if you have a server running locally. You just need to reference the local server via http (not file://), like:

http://localhost/my_picture.jpg

if picture.jpg is in your local server's webroot folder. You can do this for any site if you open your browser's developer tools and change the img element's src attribute to the local server's URL for the image. If you have access to the HTML of your site, then change it there. But obviously if someone not on your local computer/server accesses the site, they will get a broken image unless they happen to be running a local server as well and have an image with the same filename, which would be weird.

Insert new column into table in sqlite?

ALTER TABLE {tableName} ADD COLUMN COLNew {type};
UPDATE {tableName} SET COLNew = {base on {type} pass value here};

This update is required to handle the null value, inputting a default value as you require. As in your case, you need to call the SELECT query and you will get the order of columns, as paxdiablo already said:

SELECT name, colnew, qty, rate FROM{tablename}

and in my opinion, your column name to get the value from the cursor:

private static final String ColNew="ColNew";
String val=cursor.getString(cursor.getColumnIndex(ColNew));

so if the index changes your application will not face any problems.

This is the safe way in the sense that otherwise, if you are using CREATE temptable or RENAME table or CREATE, there would be a high chance of data loss if not handled carefully, for example in the case where your transactions occur while the battery is running out.

Determine version of Entity Framework I am using?

For .NET Core, this is how I'll know the version of EntityFramework that I'm using. Let's assume that the name of my project is DemoApi, I have the following at my disposal:

  1. I'll open the DemoApi.csproj file and take a look at the package reference, and there I'll get to see the version of EntityFramework that I'm using.
  2. Open up Command Prompt, Powershell or Terminal as the case maybe, change the directory to DemoApi and then enter this command: dotnet list DemoApi.csproj package

How to remove item from array by value?

Check out this way:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

and in a function:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

Java naming convention for static final variables

Don't live fanatically with the conventions that SUN have med up, do whats feel right to you and your team.

For example this is how eclipse do it, breaking the convention. Try adding implements Serializable and eclipse will ask to generate this line for you.

Update: There were special cases that was excluded didn't know that. I however withholds to do what you and your team seems fit.

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Array oList = ((from m in dc.Reviews
                           join n in dc.Users on m.authorID equals n.userID
                           orderby m.createdDate descending
                           where m.foodID == _id                      
                           select new
                           {
                               authorID = m.authorID,
                               createdDate = m.createdDate,
                               review = m.review1,
                               author = n.username,
                               profileImgUrl = n.profileImgUrl
                           }).Take(2)).ToArray();

Is there an exponent operator in C#?

I'm surprised no one has mentioned this, but for the simple (and probably most encountered) case of squaring, you just multiply by itself.

float someNumber;

float result = someNumber * someNumber;

How to list npm user-installed packages?

Use npm list and filter by contains using grep

Example:

npm list -g | grep name-of-package

How to detect a loop in a linked list?

boolean hasCycle(Node head) {

    boolean dec = false;
    Node first = head;
    Node sec = head;
    while(first != null && sec != null)
    {
        first = first.next;
        sec = sec.next.next;
        if(first == sec )
        {
            dec = true;
            break;
        }

    }
        return dec;
}

Use above function to detect a loop in linkedlist in java.

Spring JUnit: How to Mock autowired component in autowired component

Another approach in integration testing is to define a new Configuration class and provide it as your @ContextConfiguration. Into the configuration you will be able to mock your beans and also you must define all types of beans which you are using in test/s flow. To provide an example :

@RunWith(SpringRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class MockTest{
 @Configuration
 static class ContextConfiguration{
 // ... you beans here used in test flow
 @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders.standaloneSetup(/*you can declare your controller beans defines on top*/)
                .addFilters(/*optionally filters*/).build();
    }
 //Defined a mocked bean
 @Bean
    public MyService myMockedService() {
        return Mockito.mock(MyService.class);
    }
 }

 @Autowired
 private MockMvc mockMvc;

 @Autowired
 MyService myMockedService;

 @Before
 public void setup(){
  //mock your methods from MyService bean 
  when(myMockedService.myMethod(/*params*/)).thenReturn(/*my answer*/);
 }

 @Test
 public void test(){
  //test your controller which trigger the method from MyService
  MvcResult result = mockMvc.perform(get(CONTROLLER_URL)).andReturn();
  // do your asserts to verify
 }
}

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

How to download/upload files from/to SharePoint 2013 using CSOM?

I would suggest reading some Microsoft documentation on what you can do with CSOM. This might be one example of what you are looking for, but there is a huge API documented in msdn.

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.Items.GetById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery(); 

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

AngularJS : Clear $watch

$watch returns a deregistration function. Calling it would deregister the $watcher.

var listener = $scope.$watch("quartz", function () {});
// ...
listener(); // Would clear the watch

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

  1. type Ctrl+Alt+S (or go to Preferences)
  2. go to the Plugins tab, press "Browse repositories" button
  3. search:
    Visual Paradigm SDE for IntellIJ (Community edition) Modelling Case Tool
  4. install it.

You need to install proper software. Now it should works well.

I guess that UML Class Diagram is only available on Ultimate Edition.

To show UML diagram click right mouse button on specific class -> Diagrams -> Show diagram... Or you can in editor click Ctrl+Alt+Shift+U. You could append new classes to diagram by drag and drop. On the top of window you could choose more options. To save UML you should just click on save icon.

UnsatisfiedDependencyException: Error creating bean with name

I just added the @Repository annotation to Repository interface and @EnableJpaRepositories ("domain.repositroy-package") to the main class. It worked just fine.

Cursor inside cursor

I don't fully understand what was the problem with the "update current of cursor" but it is solved by using the fetch statement twice for the inner cursor:

FETCH NEXT FROM INNER_CURSOR

WHILE (@@FETCH_STATUS <> -1)
BEGIN

UPDATE CONTACTS
SET INDEX_NO = @COUNTER
WHERE CURRENT OF INNER_CURSOR

SET @COUNTER = @COUNTER + 1

FETCH NEXT FROM INNER_CURSOR
FETCH NEXT FROM INNER_CURSOR
END

Forbidden You don't have permission to access / on this server

Found my solution on Apache/2.2.15 (Unix).

And Thanks for answer from @QuantumHive:

First: I finded all

Order allow,deny
Deny from all

instead of

Order allow,deny

Allow from all

and then:

I setted

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>
#        Order allow,deny
#        Allow from all
#    </Limit>
#    <LimitExcept GET POST OPTIONS>
#        Order deny,allow
#        Deny from all
#    </LimitExcept>
#</Directory>

Remove the previous "#" annotation to

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
    AllowOverride FileInfo AuthConfig Limit
    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
    <Limit GET POST OPTIONS>
        Order allow,deny
        Allow from all
    </Limit>
    <LimitExcept GET POST OPTIONS>
        Order deny,allow
        Deny from all
    </LimitExcept>
</Directory>

ps. my WebDir is: /var/www/html

Detect iPhone/iPad purely by css

This is how I handle iPhone (and similar) devices [not iPad]:

In my CSS file:

@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
   /* CSS overrides for mobile here */
}

In the head of my HTML document:

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">

Change Activity's theme programmatically

user1462299's response works great, but if you include fragments, they will use the original activities theme. To apply the theme to all fragments as well you can override the getTheme() method of the Context instead:

@Override
public Resources.Theme getTheme() {
    Resources.Theme theme = super.getTheme();
    if(useAlternativeTheme){
        theme.applyStyle(R.style.AlternativeTheme, true);
    }
    // you could also use a switch if you have many themes that could apply
    return theme;
}

You do not need to call setTheme() in the onCreate() Method anymore. You are overriding every request to get the current theme within this context this way.

How to have a transparent ImageButton: Android

Setting the background to "@null" will make the button have no effect when clicked. This will be a better choice.

style="?android:attr/borderlessButtonStyle"

Later I found that using

android:background="?android:attr/selectableItemBackground"

is also a good solution. And you can inherit this attribute in your own style.

Difference between View and ViewGroup in Android

in ViewGroup you can add some other Views as child. ViewGroup is the base class for layouts and view containers.

ruby 1.9: invalid byte sequence in UTF-8

The accepted answer nor the other answer work for me. I found this post which suggested

string.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')

This fixed the problem for me.

How do you get current active/default Environment profile programmatically in Spring?

@Value("${spring.profiles.active}")
private String activeProfile;

It works and you don't need to implement EnvironmentAware. But I don't know drawbacks of this approach.

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

Repeat table headers in print mode

Chrome and Opera browsers do not support thead {display: table-header-group;} but rest of others support properly..

How to download image using requests

Following code snippet downloads a file.

The file is saved with its filename as in specified url.

import requests

url = "http://example.com/image.jpg"
filename = url.split("/")[-1]
r = requests.get(url, timeout=0.5)

if r.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(r.content)

ASP.NET Identity DbContext confusion

I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.

using awk with column value conditions

Depending on the AWK implementation are you using == is ok or not.

Have you tried ~?. For example, if you want $1 to be "hello":

awk '$1 ~ /^hello$/{ print $3; }' <infile>

^ means $1 start, and $ is $1 end.

How to make a local variable (inside a function) global

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Pyspark: Exception: Java gateway process exited before sending the driver its port number

Had the same issue with my iphython notebook (IPython 3.2.1) on Linux (ubuntu).

What was missing in my case was setting the master URL in the $PYSPARK_SUBMIT_ARGS environment like this (assuming you use bash):

export PYSPARK_SUBMIT_ARGS="--master spark://<host>:<port>"

e.g.

export PYSPARK_SUBMIT_ARGS="--master spark://192.168.2.40:7077"

You can put this into your .bashrc file. You get the correct URL in the log for the spark master (the location for this log is reported when you start the master with /sbin/start_master.sh).

TypeError: Converting circular structure to JSON in nodejs

I came across this issue when not using async/await on a asynchronous function (api call). Hence adding them / using the promise handlers properly cleared the error.

Can't access object property, even though it shows up in a console log

For me it turned out to be a Mongoose-related problem.

I was looping over objects that I got from a Mongo query. I just had to remove:

items = await Model.find()

And replace it by:

items = await Model.find().lean()

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

I have seen many solutions in the above.

Here I am using map function to find the index of the search text in an array object.

I am going to explain my answer with using students data.

  • step 1: create array object for the students(optional you can create your own array object).
    var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];

  • step 2: Create variable to search text
    var studentNameToSearch = "Divya";

  • step 3: Create variable to store matched index(here we use map function to iterate).
    var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);

_x000D_
_x000D_
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];_x000D_
_x000D_
var studentNameToSearch = "Divya";_x000D_
_x000D_
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);_x000D_
_x000D_
console.log(matchedIndex);_x000D_
_x000D_
alert("Your search name index in array is:"+matchedIndex)
_x000D_
_x000D_
_x000D_

Stashing only staged changes in git - is it possible?

TL;DR; git stash-staged

After creating an alias:

git config --global alias.stash-staged '!bash -c "git stash -- \$(git diff --staged --name-only)"'

Here git diff returns list of --staged files --name-only
And then we pass this list as pathspec to git stash commad.

From man git stash:

git stash [--] [<pathspec>...]

<pathspec>...
   The new stash entry records the modified states only for the files
   that match the pathspec. The index entries and working tree
   files are then rolled back to the state in HEAD only for these
   files, too, leaving files that do not match the pathspec intact.

Finding element in XDocument?

Sebastian's answer was the only answer that worked for me while examining a xaml document. If, like me, you'd like a list of all the elements then the method would look a lot like Sebastian's answer above but just returning a list...

    private static List<XElement> GetElements(XDocument doc, string elementName)
    {
        List<XElement> elements = new List<XElement>();

        foreach (XNode node in doc.DescendantNodes())
        {
            if (node is XElement)
            {
                XElement element = (XElement)node;
                if (element.Name.LocalName.Equals(elementName))
                    elements.Add(element);
            }
        }
        return elements;
    }

Call it thus:

var elements = GetElements(xamlFile, "Band");

or in the case of my xaml doc where I wanted all the TextBlocks, call it thus:

var elements = GetElements(xamlFile, "TextBlock");

Convert blob URL to normal URL

Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:

function blobToDataURL(blob, callback) {
  var fileReader = new FileReader();
  fileReader.onload = function(e) {callback(e.target.result);}
  fileReader.readAsDataURL(blob);
}

DropdownList DataSource

You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable.
Main you have to consider three thing while binding the datasource of a dropdown.

  1. DataSource - Name of the dataset or datatable or your datasource
  2. DataValueField - These field will be hidden
  3. DataTextField - These field will be displayed on the dropdwon.

you can use following code to bind a dropdownlist to a datasource as a datatable:

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

    SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);

    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt=new DataTable();
    da.Fill(dt);

    DropDownList1.DataTextField = "QUIZ_Name";
    DropDownList1.DataValueField = "QUIZ_ID"

    DropDownList1.DataSource = dt;
    DropDownList1.DataBind();

if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true" you can use SelectedIndexChanged event to write your code.

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string strQUIZ_ID=DropDownList1.SelectedValue;
    string strQUIZ_Name=DropDownList1.SelectedItem.Text;
    // Your code..............
}

iPhone app could not be installed at this time

I just saw this as a result of a network error / time-out on a flaky network. I could see the progress bar increasing after I got the bright idea of just retrying. Also saw HTTP Range requests on the download server with ever increasing offsets of a few megabytes (the entire app was about 44MB).

Detecting superfluous #includes in C/C++?

CLion, the C/C++ IDE from JetBrains, detects redundant includes out-of-the-box. These are grayed-out in the editor, but there are also functions to optimise includes in the current file or whole project.

I've found that you pay for this functionality though; CLion takes a while to scan and analyse your project when first loaded.

What is WEB-INF used for in a Java EE web application?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.

WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.

Generally speaking, many configurations files also go into WEB-INF.

As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).

error: command 'gcc' failed with exit status 1 on CentOS

pip install -U pip
pip install -U cython

Fragments onResume from back stack

The following section at Android Developers describes a communication mechanism Creating event callbacks to the activity. To quote a line from it:

A good way to do that is to define a callback interface inside the fragment and require that the host activity implement it. When the activity receives a callback through the interface, it can share the information with other fragments in the layout as necessary.

Edit: The fragment has an onStart(...) which is invoked when the fragment is visible to the user. Similarly an onResume(...) when visible and actively running. These are tied to their activity counterparts. In short: use onResume()

How to select rows for a specific date, ignoring time in SQL Server

select * from sales where salesDate between '11/11/2010' and '12/11/2010' --if using dd/mm/yyyy

The more correct way to do it:

DECLARE @myDate datetime
SET @myDate = '11/11/2010'
select * from sales where salesDate>=@myDate and salesDate<dateadd(dd,1,@myDate)

If only the date is specified, it means total midnight. If you want to make sure intervals don't overlap, switch the between with a pair of >= and <

you can do it within one single statement, but it's just that the value is used twice.

Waiting for Target Device to Come Online

None of solutions above worked for me, so I had to wipe content of

C:\Users\your_name\.android\avd

and re-create emulated device

Kill Attached Screen in Linux

You can find the process id of the attached running screen. I found it same as the session id which you can get by command:
screen -ls
And you can use following command to kill that process:
kill [sessionId] or
sudo kill [sessionId]

Printing a java map Map<String, Object> - How?

I'm sure there's some nice library that does this sort of thing already for you... But to just stick with the approach you're already going with, Map#entrySet gives you a combined Object with the key and the value. So something like:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}

will do what you're after.


If you're using java 8, there's also the new streaming approach.

map.forEach((key, value) -> System.out.println(key + ":" + value));

How to find index of all occurrences of element in array?

Note: MDN gives a method using a while loop:

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}

I wouldn't say it's any better than other answers. Just interesting.

Remove a marker from a GoogleMap

The method signature for addMarker is:

public final Marker addMarker (MarkerOptions options)

So when you add a marker to a GoogleMap by specifying the options for the marker, you should save the Marker object that is returned (instead of the MarkerOptions object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove() to remove it from the map.

As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean).

Using LINQ to concatenate strings

Real example from my code:

return selected.Select(query => query.Name).Aggregate((a, b) => a + ", " + b);

A query is an object that has a Name property which is a string, and I want the names of all the queries on the selected list, separated by commas.

How to hide the border for specified rows of a table?

Add programatically noborder class to specific row to hide it

<style>
     .noborder
      {
        border:none;
      }
    </style>

<table>

    <tr>
       <th>heading1</th>
       <th>heading2</th>
    </tr>


    <tr>
       <td>content1</td>
       <td>content2</td>
    </tr>
    /*no border for this row */
    <tr class="noborder">
       <td>content1</td>
       <td>content2</td>
    </tr>

</table>

How do I check in python if an element of a list is empty?

Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.

if not A[i]:
    ## do whatever

Anyway if you know the size of your list then you don't need to do all this.

How to launch Windows Scheduler by command-line?

You can use either TASKSCHD.MSC or CONTROL SCHEDTASKS

Here are some more such commands.

Phonegap + jQuery Mobile, real world sample or tutorial

This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )

And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd

Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.

I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?

Fastest way to check a string contain another substring in JavaScript?

Does this work for you?

string1.indexOf(string2) >= 0

Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.

Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.

Passing a string array as a parameter to a function java

I believe this should be the way this is done...

public void function(String [] array){
....
}

And the calling will be done like...

public void test(){
    String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
    function(stringArray);
}

Using node.js as a simple web server

A slightly more verbose express 4.x version but that provides directory listing, compression, caching and requests logging in a minimal number of lines

var express = require('express');
var compress = require('compression');
var directory = require('serve-index');
var morgan = require('morgan'); //logging for express

var app = express();

var oneDay = 86400000;

app.use(compress());
app.use(morgan());
app.use(express.static('filesdir', { maxAge: oneDay }));
app.use(directory('filesdir', {'icons': true}))

app.listen(process.env.PORT || 8000);

console.log("Ready To serve files !")

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How do I send a POST request as a JSON?

You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4

code:

    import urllib2,json

    url = 'http://www.google.com/someservice'
    postdata = {'key':'value'}

    req = urllib2.Request(url)
    req.add_header('Content-Type','application/json')
    data = json.dumps(postdata)

    response = urllib2.urlopen(req,data)

What are some good SSH Servers for windows?

OpenSSH is a contender. Looks like it hasn't been updated in a while though.

It's the de facto choice in my opinion. And yes, running under Cygwin is really the nicest method.

What is the default database path for MongoDB?

The Windows x64 installer shows the a path in the installer UI/wizard.

You can confirm which path it used later, by opening your mongod.cfg file. My mongod.cfg was located here C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg (change for your version of MongoDB!

When I opened my mongd.cfg I found this line, showing the default db path:

dbPath: C:\Program Files\MongoDB\Server\4.0\data

However, this caused an error when trying to run mongod, which was still expecting to find C:\data\db:

2019-05-05T09:32:36.084-0700 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory C:\data\db\ not found., terminating

You could pass mongod a --dbpath=... parameter. In my case:

mongod --dbpath="C:\Program Files\MongoDB\Server\4.0\data"

How to search for an element in a golang slice

As other guys commented before you can write your own procedure with anonymous function to solve this issue.

I used two ways to solve it:

func Find(slice interface{}, f func(value interface{}) bool) int {
    s := reflect.ValueOf(slice)
    if s.Kind() == reflect.Slice {
        for index := 0; index < s.Len(); index++ {
            if f(s.Index(index).Interface()) {
                return index
            }
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 12,
    }) 
    
    idx := Find(destinationList, func(value interface{}) bool {
        return value.(UserInfo).UserId == userId
    })
    
    if idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

Second method with less computational cost:

func Search(length int, f func(index int) bool) int {
    for index := 0; index < length; index++ {
        if f(index) {
            return index
        }
    }
    return -1
}

Uses example:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 123,
    }) 
    
    idx := Search(len(destinationList), func(index int) bool {
        return destinationList[index].UserId == userId
    })
    
    if  idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

For me worked adding the following section to web.config file:

<configuration>
...
    <runtime>
    ...
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http.WebHost" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
        </dependentAssembly>
    ...
    </runtime>
...
</configuration>

This example stands for MVC 5.1. Hope it will help someone to resolve such issue.

CSS 100% height with padding/margin

There is a new property in CSS3 that you can use to change the way the box model calculates width/height, it's called box-sizing.

By setting this property with the value "border-box" it makes whichever element you apply it to not stretch when you add a padding or border. If you define something with 100px width, and 10px padding, it will still be 100px wide.

box-sizing: border-box;

See here for browser support. It does not work for IE7 and lower, however, I believe that Dean Edward's IE7.js adds support for it. Enjoy :)

How to set a cookie for another domain

see RFC6265:

The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server. For example, the user agent will accept a cookie with a Domain attribute of "example.com" or of "foo.example.com" from foo.example.com, but the user agent will not accept a cookie with a Domain attribute of "bar.example.com" or of "baz.foo.example.com".

NOTE: For security reasons, many user agents are configured to reject Domain attributes that correspond to "public suffixes". For example, some user agents will reject Domain attributes of "com" or "co.uk". (See Section 5.3 for more information.)

But the above mentioned workaround with image/iframe works, though it's not recommended due to its insecurity.

Memory address of an object in C#

When you free that handle, the garbage collector is free to move the memory that was pinned. If you have a pointer to memory that's supposed to be pinned, and you un-pin that memory, then all bets are off. That this worked at all in 3.5 was probably just by luck. The JIT compiler and the runtime for 4.0 probably do a better job of object lifetime analysis.

If you really want to do this, you can use a try/finally to prevent the object from being un-pinned until after you've used it:

public static string Get(object a)
{
    GCHandle handle = GCHandle.Alloc(a, GCHandleType.Pinned);
    try
    {
        IntPtr pointer = GCHandle.ToIntPtr(handle);
        return "0x" + pointer.ToString("X");
    }
    finally
    {
        handle.Free();
    }
}

HTML5 Video Stop onClose

Someone already has the answer.

$('video') will return an array of video items. It is totally a valid seletor!

so

$("video").each(function () { this.pause() });

will work.

Typing Greek letters etc. in Python plots

You need to make the strings raw and use latex:

fig.gca().set_ylabel(r'$\lambda$')

As of matplotlib 2.0 the default font supports most western alphabets and can simple do

ax.set_xlabel('?')

with unicode.

Unsupported method: BaseConfig.getApplicationIdSuffix()

First, open your application module build.gradle file.

Check the classpath according to your project dependency. If not change the version of this classpath.

from:

classpath 'com.android.tools.build:gradle:1.0.0'

To:

classpath 'com.android.tools.build:gradle:2.3.2'

or higher version according to your gradle of android studio.

If its still problem, then change buildToolsVersion:

From:

buildToolsVersion '21.0.0'

To:

buildToolsVersion '25.0.0'

then hit 'Try again' and gradle will automatically sync. This will solve it.

How to get my project path?

Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../.. to get your project's path.

Convert regular Python string to raw string

For Python 3, the way to do this that doesn't add double backslashes and simply preserves \n, \t, etc. is:

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)

Which gives a value that can be written as CSV:

hello\nbobby\nsally\n

There doesn't seem to be a solution for other special characters, however, that may get a single \ before them. It's a bummer. Solving that would be complex.

For example, to serialize a pandas.Series containing a list of strings with special characters in to a textfile in the format BERT expects with a CR between each sentence and a blank line between each document:

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')

This outputs (for the Github CodeSearchNet docstrings for all languages tokenized into sentences):

Makes sure the fast-path emits in order.
@param value the value to emit or queue up\n@param delayError if true, errors are delayed until the source has terminated\n@param disposable the resource to dispose if the drain terminates

Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends\na termination notification.
Scheduler:\n{@code amb} does not operate by default on a particular {@link Scheduler}.
@param  the common element type\n@param sources\nan Iterable of ObservableSource sources competing to react first.
A subscription to each source will\noccur in the same order as in the Iterable.
@return an Observable that emits the same sequence as whichever of the source ObservableSources first\nemitted an item or sent a termination notification\n@see ReactiveX operators documentation: Amb


...

Plotting dates on the x-axis with Python's matplotlib

You can do this more simply using plot() instead of plot_date().

First, convert your strings to instances of Python datetime.date:

import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here

Then plot:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()

Result:

enter image description here

How to install python modules without root access?

If you have to use a distutils setup.py script, there are some commandline options for forcing an installation destination. See http://docs.python.org/install/index.html#alternate-installation. If this problem repeats, you can setup a distutils configuration file, see http://docs.python.org/install/index.html#inst-config-files.

Setting the PYTHONPATH variable is described in tihos post.

Target class controller does not exist - Laravel 8

I got the same error when I installed Laravel version 8.27.0: The error is as follow:

The Error that I got:

But when I saw my app/Providers/RouteServiceProvider.php I have namespaces inside my boot method, then I just uncommented this => "protected $namespace = 'App\Http\Controllers';"

Just Uncomment The protected $namespace = 'App\Http\Controllers';';

Now My Project is working:

Project is working safe and sound

What's the best UML diagramming tool?

You might want to take a look at MagicDraw or Visual Paradigm for UML. Both offer community editions that, of course, don't span the full feature range, but may well be sufficient if you want to create diagrams only and not generate code or do full round-trip engineering.

ASP.NET page life cycle explanation

There are 10 events in ASP.NET page life cycle, and the sequence is:

  1. Init
  2. Load view state
  3. Post back data
  4. Load
  5. Validate
  6. Events
  7. Pre-render
  8. Save view state
  9. Render
  10. Unload

Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.

ASP.NET life cycle

Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010

Are HTTP cookies port specific?

I was experiencing a similar problem running (and trying to debug) two different Django applications on the same machine.

I was running them with these commands:

./manage.py runserver 8000
./manage.py runserver 8001

When I did login in the first one and then in the second one I always got logged out the first one and viceversa.

I added this on my /etc/hosts

127.0.0.1    app1
127.0.0.1    app2

Then I started the two apps with these commands:

./manage.py runserver app1:8000
./manage.py runserver app2:8001

Problem solved :)

How can I convert my Java program to an .exe file?

The latest Java Web Start has been enhanced to allow good offline operation as well as allowing "local installation". It is worth looking into.

EDIT 2018: Java Web Start is no longer bundled with the newest JDK's. Oracle is pushing towards a "deploy your app locally with an enclosed JRE" model instead.

Get last 30 day records from today date in SQL Server

you can use this to get the data of the last 30 days based on a column.

WHERE DATEDIFF(dateColumn,CURRENT_TIMESTAMP) BETWEEN 0 AND 30

CSS media query to target iPad and iPad only?

Finally found a solution from : Detect different device platforms using CSS

<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
<link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />

To reduce HTTP call, this can also be used inside you existing common CSS file:

@media all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait) {
  .ipad-portrait { color: red; } /* your css rules for ipad portrait */
}
@media all and (device-width: 1024px) and (device-height: 768px) and (orientation:landscape) {
  .ipad-landscape { color: blue; } /* your css rules for ipad landscape */
}

Hope this helps.

Other references:

Changing factor levels with dplyr mutate

Maybe you are looking for this plyr::revalue function:

mutate(dat, x = revalue(x, c("A" = "B")))

You can see plyr::mapvalues too.

How can I determine if a variable is 'undefined' or 'null'?

The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...

The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined.

Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:

if (foo === void 0 || foo === null) { ... }

How do I delete a Git branch locally and remotely?

The short answers

If you want more detailed explanations of the following commands, then see the long answers in the next section.

Deleting a remote branch

git push origin --delete <branch>  # Git version 1.7.0 or newer
git push origin -d <branch>        # Shorter version (Git 1.7.0 or newer)
git push origin :<branch>          # Git versions older than 1.7.0

Deleting a local branch

git branch --delete <branch>
git branch -d <branch> # Shorter version
git branch -D <branch> # Force-delete un-merged branches

Deleting a local remote-tracking branch

git branch --delete --remotes <remote>/<branch>
git branch -dr <remote>/<branch> # Shorter

git fetch <remote> --prune # Delete multiple obsolete remote-tracking branches
git fetch <remote> -p      # Shorter

The long answer: there are three different branches to delete!

When you're dealing with deleting branches both locally and remotely, keep in mind that there are three different branches involved:

  1. The local branch X.
  2. The remote origin branch X.
  3. The local remote-tracking branch origin/X that tracks the remote branch X.

Visualization of three branches

The original poster used:

git branch -rd origin/bugfix

Which only deleted his local remote-tracking branch origin/bugfix, and not the actual remote branch bugfix on origin.

Diagram 2

To delete that actual remote branch, you need

git push origin --delete bugfix

Diagram 3

Additional details

The following sections describe additional details to consider when deleting your remote and remote-tracking branches.

Pushing to delete remote branches also removes remote-tracking branches

Note that deleting the remote branch X from the command line using a git push will also remove the local remote-tracking branch origin/X, so it is not necessary to prune the obsolete remote-tracking branch with git fetch --prune or git fetch -p. However, it wouldn't hurt if you did it anyway.

You can verify that the remote-tracking branch origin/X was also deleted by running the following:

# View just remote-tracking branches
git branch --remotes
git branch -r

# View both strictly local as well as remote-tracking branches
git branch --all
git branch -a

Pruning the obsolete local remote-tracking branch origin/X

If you didn't delete your remote branch X from the command line (like above), then your local repository will still contain (a now obsolete) remote-tracking branch origin/X. This can happen if you deleted a remote branch directly through GitHub's web interface, for example.

A typical way to remove these obsolete remote-tracking branches (since Git version 1.6.6) is to simply run git fetch with the --prune or shorter -p. Note that this removes all obsolete local remote-tracking branches for any remote branches that no longer exist on the remote:

git fetch origin --prune
git fetch origin -p # Shorter

Here is the relevant quote from the 1.6.6 release notes (emphasis mine):

"git fetch" learned --all and --multipleoptions, to run fetch from many repositories, and --prune option to remove remote tracking branches that went stale. These make "git remote update" and "git remote prune" less necessary (there is no plan to remove "remote update" nor "remote prune", though).

Alternative to above automatic pruning for obsolete remote-tracking branches

Alternatively, instead of pruning your obsolete local remote-tracking branches through git fetch -p, you can avoid making the extra network operation by just manually removing the branch(es) with the --remote or -r flags:

git branch --delete --remotes origin/X
git branch -dr origin/X # Shorter

See Also

How to pass prepareForSegue: an object

I've implemented a library with a category on UIViewController that simplifies this operation. Basically, you set the parameters you want to pass over in a NSDictionary associated to the UI item that is performing the segue. It works with manual segues too.

For example, you can do

[self performSegueWithIdentifier:@"yourIdentifier" parameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

for a manual segue or create a button with a segue and use

[button setSegueParameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

If destination view controller is not key-value coding compliant for a key, nothing happens. It works with key-values too (useful for unwind segues). Check it out here https://github.com/stefanomondino/SMQuickSegue

How should I validate an e-mail address?

Use simple one line code for email Validation

public static boolean isValidEmail(CharSequence target) {
    return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

use like...

if (!isValidEmail(yourEdittext.getText().toString()) {
    Toast.makeText(context, "your email is not valid", 2000).show();
}

What could cause java.lang.reflect.InvocationTargetException?

Use the getCause() method on the InvocationTargetException to retrieve the original exception.

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

my problem is solved by

composer update
composer install
php artisan key:generate

if you any other problem you can clear cache and config Clear Route cache:

php artisan route:cache

Clear View cache:

php artisan view:clear

Clear Config cache:

php artisan config:cache

How do I execute a Shell built-in command with a C function?

If you just want to execute the shell command in your c program, you could use,

   #include <stdlib.h>

   int system(const char *command);

In your case,

system("pwd");

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.

What do you mean by this? You should be able to find the mentioned packages in /bin/

sudo find / -executable -name pwd
sudo find / -executable -name echo

Failed Apache2 start, no error log

I also just ran in to a similar problem, that is service apache2 reload fails but prints no useful information. This is because the script in /etc/init.d/apache (on Debian, at least) eats the output of the apache2ctl configtest command it runs to sanitize the Apache config.

An easy solution to get a more meaningful explanation for the failure is to run apache2ctl configtest again yourself, which will print the (hopefully useful) error messages to the console.

What is the difference between match_parent and fill_parent?

match_parent is used in place of fill_parent and sets it to go as far as the parent goes. Just use match_parent and forget about fill_parent. I completely ditched fill_parent and everything is perfect as usual.

Check here for more.

How To Convert A Number To an ASCII Character?

you can simply cast it.

char c = (char)100;

Checking Maven Version

Type the command mvn -version directly in your maven directory, you probably haven't added it to your PATH. Here are explained details of how to add maven to your PATH variable (I guess you use Windows because you are talking about CMD).

Problems installing the devtools package

I'm on windows and had the same issue.

I used the below code :

install.packages("devtools", type = "win.binary")

Then library(devtools) worked for me.

How to call a JavaScript function from PHP?

try like this

<?php
 if(your condition){
     echo "<script> window.onload = function() {
     yourJavascriptFunction(param1, param2);
 }; </script>";
?>

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

How to get the command line args passed to a running process on unix/linux systems?

try ps -n in a linux terminal. This will show:

1.All processes RUNNING, their command line and their PIDs

  1. The program intiate the processes.

Afterwards you will know which process to kill

What is the difference between decodeURIComponent and decodeURI?

js> s = "http://www.example.com/string with + and ? and & and spaces";
http://www.example.com/string with + and ? and & and spaces
js> encodeURI(s)
http://www.example.com/string%20with%20+%20and%20?%20and%20&%20and%20spaces
js> encodeURIComponent(s)
http%3A%2F%2Fwww.example.com%2Fstring%20with%20%2B%20and%20%3F%20and%20%26%20and%20spaces

Looks like encodeURI produces a "safe" URI by encoding spaces and some other (e.g. nonprintable) characters, whereas encodeURIComponent additionally encodes the colon and slash and plus characters, and is meant to be used in query strings. The encoding of + and ? and & is of particular importance here, as these are special chars in query strings.

slideToggle JQuery right to left

I would suggest you use the below css

.showhideoverlay { 
  width: 100%;
  height: 100%;
  right: 0px;
  top: 0px;
  position: fixed;
  background: #000;
  opacity: 0.75;
}

You can then use a simple toggle function:

$('a.open').click(function() {
  $('div.showhideoverlay').toggle("slow");
});

This will display the overlay menu from right to left. Alternatively, you can use the positioning for changing the effect from top or bottom, i.e. use bottom: 0; instead of top: 0; - you will see menu sliding from right-bottom corner.

Convert a Map<String, String> to a POJO

Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).

Use ObjectMapper's convertValue method:

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);

No need to convert into JSON string or something else; direct conversion does much faster.

String.Replace(char, char) method in C#

string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);

Obviously, this removes both '\n' and '\r' and is as simple as I know how to do it.

Iterate through Nested JavaScript Objects

You can create a recursive function like this to do a depth-first traversal of the cars object.

var findObjectByLabel = function(obj, label) {
    if(obj.label === label) { return obj; }
    for(var i in obj) {
        if(obj.hasOwnProperty(i)){
            var foundLabel = findObjectByLabel(obj[i], label);
            if(foundLabel) { return foundLabel; }
        }
    }
    return null;
};

which can be called like so

findObjectByLabel(car, "Chevrolet");

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

How do I capture the output of a script if it is being ran by the task scheduler?

You can have a debug.cmd that calls yourscript.cmd

yourscript.cmd > logall.txt

you schedule debug.cmd instead of yourscript.cmd

How can I tell if a VARCHAR variable contains a substring?

    IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS

    IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS

    Additionally we can also use LIKE but I usually don't use LIKE.

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>
        </c:if>
    </c:forEach>
</select>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    System.out.println(productSubCategoryName);
    map.put(productSubCategoryName, true);
}
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>
    </c:forEach>
</select>

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I usually use float: left; and add overflow: auto; to solve the collapsing parent problem (as to why this works, overflow: auto will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.

The reason I don't use display: table-cell is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.

The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.

enter image description here

React: why child component doesn't update when prop changes

Confirmed, adding a Key works. I went through the docs to try and understand why.

React wants to be efficient when creating child components. It won't render a new component if it's the same as another child, which makes the page load faster.

Adding a Key forces React to render a new component, thus resetting State for that new component.

https://reactjs.org/docs/reconciliation.html#recursing-on-children

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

how does Request.QueryString work?

The QueryString collection is used to retrieve the variable values in the HTTP query string.

The HTTP query string is specified by the values following the question mark (?), like this:

Link with a query string

The line above generates a variable named txt with the value "this is a query string test".

Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.

And see this sample : http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString

refer this : http://www.dotnetperls.com/querystring

you can collect More details in google .

Fastest way to check if a file exist using standard C++/C++11/C?

I need a fast function that can check if a file is exist or not and PherricOxide's answer is almost what I need except it does not compare the performance of boost::filesystem::exists and open functions. From the benchmark results we can easily see that :

  • Using stat function is the fastest way to check if a file is exist. Note that my results are consistent with that of PherricOxide's answer.

  • The performance of boost::filesystem::exists function is very close to that of stat function and it is also portable. I would recommend this solution if boost libraries is accessible from your code.

Benchmark results obtained with Linux kernel 4.17.0 and gcc-7.3:

2018-05-05 00:35:35
Running ./filesystem
Run on (8 X 2661 MHz CPU s)
CPU Caches:
  L1 Data 32K (x4)
  L1 Instruction 32K (x4)
  L2 Unified 256K (x4)
  L3 Unified 8192K (x1)
--------------------------------------------------
Benchmark           Time           CPU Iterations
--------------------------------------------------
use_stat          815 ns        813 ns     861291
use_open         2007 ns       1919 ns     346273
use_access       1186 ns       1006 ns     683024
use_boost         831 ns        830 ns     831233

Below is my benchmark code:

#include <string.h>                                                                                                                                                                                                                                           
#include <stdlib.h>                                                                                                                                                                                                                                           
#include <sys/types.h>                                                                                                                                                                                                                                        
#include <sys/stat.h>                                                                                                                                                                                                                                         
#include <unistd.h>                                                                                                                                                                                                                                           
#include <dirent.h>                                                                                                                                                                                                                                           
#include <fcntl.h>                                                                                                                                                                                                                                            
#include <unistd.h>                                                                                                                                                                                                                                           

#include "boost/filesystem.hpp"                                                                                                                                                                                                                               

#include <benchmark/benchmark.h>                                                                                                                                                                                                                              

const std::string fname("filesystem.cpp");                                                                                                                                                                                                                    
struct stat buf;                                                                                                                                                                                                                                              

// Use stat function                                                                                                                                                                                                                                          
void use_stat(benchmark::State &state) {                                                                                                                                                                                                                      
    for (auto _ : state) {                                                                                                                                                                                                                                    
        benchmark::DoNotOptimize(stat(fname.data(), &buf));                                                                                                                                                                                                   
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_stat);                                                                                                                                                                                                                                          

// Use open function                                                                                                                                                                                                                                          
void use_open(benchmark::State &state) {                                                                                                                                                                                                                      
    for (auto _ : state) {                                                                                                                                                                                                                                    
        int fd = open(fname.data(), O_RDONLY);                                                                                                                                                                                                                
        if (fd > -1) close(fd);                                                                                                                                                                                                                               
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_open);                                  
// Use access function                                                                                                                                                                                                                                        
void use_access(benchmark::State &state) {                                                                                                                                                                                                                    
    for (auto _ : state) {                                                                                                                                                                                                                                    
        benchmark::DoNotOptimize(access(fname.data(), R_OK));                                                                                                                                                                                                 
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_access);                                                                                                                                                                                                                                        

// Use boost                                                                                                                                                                                                                                                  
void use_boost(benchmark::State &state) {                                                                                                                                                                                                                     
    for (auto _ : state) {                                                                                                                                                                                                                                    
        boost::filesystem::path p(fname);                                                                                                                                                                                                                     
        benchmark::DoNotOptimize(boost::filesystem::exists(p));                                                                                                                                                                                               
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_boost);                                                                                                                                                                                                                                         

BENCHMARK_MAIN();   

How to disable XDebug

For WAMP, click left click on the Wamp icon in the taskbar tray. Hover over PHP and then click on php.ini and open it in your texteditor.

Now, search for the phrase 'zend_extension' and add ; (semicolon) in front it.

Restart the WAMP and you are good to go.

How to click on hidden element in Selenium WebDriver?

First store that element in object, let's say element and then write following code to click on that hidden element:

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Main advantage of <jsp:include /> over <%@ include > is:

<jsp:include /> allows to pass parameters

<jsp:include page="inclusion.jsp">
    <jsp:param name="menu" value="objectValue"/>
</jsp:include>

which is not possible in <%@include file="somefile.jsp" %>

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

How to start Spyder IDE on Windows

Open a command prompt. Enter the command spyder. Does anything appear? If an exception is preventing it from opening, you would be able to see the reason here. If the command is not found, update your environment variables to point to the Python3.6/Scripts folder, and run spyder again (in a new cmd prompt).

Entity Framework Refresh context?

context.Reload() was not working for me in MVC 4, EF 5 so I did this.

context.Entry(entity).State = EntityState.Detached;
entity = context.Find(entity.ID);

and its working fine.