Programs & Examples On #Libxml ruby

did you register the component correctly? For recursive components, make sure to provide the "name" option

I had this error and discovered the issue was because the name of the component was identical to the name of a prop.

import Control from '@/Control.vue';
export default {
    name: 'Question',
    components: {
        Control
    },
    props: ['Control', 'source'],

I was using file components. I changed the Control.vue to InputControl.vue and this warning disappeared.

Get selected value of a dropdown's item using jQuery

HTML:

<select class="form-control" id="SecondSelect">
       <option>5<option>
       <option>10<option>
       <option>20<option>
       <option>30<option>
</select>

JavaScript:

var value = $('#SecondSelect')[0].value;

Safely remove migration In Laravel

You likely need to delete the entry from the migrations table too.

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

Before and BeforeClass in JUnit

The function @Before annotation will be executed before each of test function in the class having @Test annotation but the function with @BeforeClass will be execute only one time before all the test functions in the class.

Similarly function with @After annotation will be executed after each of test function in the class having @Test annotation but the function with @AfterClass will be execute only one time after all the test functions in the class.

SampleClass

public class SampleClass {
    public String initializeData(){
        return "Initialize";
    }

    public String processDate(){
        return "Process";
    }
 }

SampleTest

public class SampleTest {

    private SampleClass sampleClass;

    @BeforeClass
    public static void beforeClassFunction(){
        System.out.println("Before Class");
    }

    @Before
    public void beforeFunction(){
        sampleClass=new SampleClass();
        System.out.println("Before Function");
    }

    @After
    public void afterFunction(){
        System.out.println("After Function");
    }

    @AfterClass
    public static void afterClassFunction(){
        System.out.println("After Class");
    }

    @Test
    public void initializeTest(){
        Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
    }

    @Test
    public void processTest(){
        Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
    }

}

Output

Before Class
Before Function
After Function
Before Function
After Function
After Class

In Junit 5

@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll

What is the minimum I have to do to create an RPM file?

As an application distributor, fpm sounds perfect for your needs. There is an example here which shows how to package an app from source. FPM can produce both deb files and RPM files.

How to Display Multiple Google Maps per page with API V3

I needed to load dynamic number of google maps, with dynamic locations. So I ended up with something like this. Hope it helps. I add LatLng as data-attribute on map div.

So, just create divs with class "maps". Every map canvas can than have a various IDs and LatLng like this. Of course you can set up various data attributes for zoom and so...

Maybe the code might be cleaner, but it works for me pretty well.

<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>

  <script>
      var map;
      function initialize() {
        // Get all map canvas with ".maps" and store them to a variable.
        var maps = document.getElementsByClassName("maps");

        var ids, gps, mapId = '';

        // Loop: Explore all elements with ".maps" and create a new Google Map object for them
        for(var i=0; i<maps.length; i++) {

          // Get ID of single div
          mapId = document.getElementById(maps[i].id);

          // Get LatLng stored in data attribute. 
          // !!! Make sure there is no space in data-attribute !!!
          // !!! and the values are separated with comma !!!
          gps = mapId.getAttribute('data-gps');

          // Convert LatLng to an array
          gps = gps.split(",");

          // Create new Google Map object for single canvas 
          map = new google.maps.Map(mapId, {
            zoom: 15,
            // Use our LatLng array bellow
            center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            mapTypeId: 'roadmap',
            mapTypeControl: true,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            }
          });

          // Create new Google Marker object for new map
          var marker = new google.maps.Marker({
            // Use our LatLng array bellow
            position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
            map: map
          });
        }
      }
  </script>

How to put a jpg or png image into a button in HTML

You can style the button using CSS or use an image-input. Additionally you might use the button element which supports inline content.

<button type="submit"><img src="/path/to/image" alt="Submit"></button>

Does "git fetch --tags" include "git fetch"?

Note: starting with git 1.9/2.0 (Q1 2014), git fetch --tags fetches tags in addition to what are fetched by the same command line without the option.

See commit c5a84e9 by Michael Haggerty (mhagger):

Previously, fetch's "--tags" option was considered equivalent to specifying the refspec

refs/tags/*:refs/tags/*

on the command line; in particular, it caused the remote.<name>.refspec configuration to be ignored.

But it is not very useful to fetch tags without also fetching other references, whereas it is quite useful to be able to fetch tags in addition to other references.
So change the semantics of this option to do the latter.

If a user wants to fetch only tags, then it is still possible to specifying an explicit refspec:

git fetch <remote> 'refs/tags/*:refs/tags/*'

Please note that the documentation prior to 1.8.0.3 was ambiguous about this aspect of "fetch --tags" behavior.
Commit f0cb2f1 (2012-12-14) fetch --tags made the documentation match the old behavior.
This commit changes the documentation to match the new behavior (see Documentation/fetch-options.txt).

Request that all tags be fetched from the remote in addition to whatever else is being fetched.


Since Git 2.5 (Q2 2015) git pull --tags is more robust:

See commit 19d122b by Paul Tan (pyokagan), 13 May 2015.
(Merged by Junio C Hamano -- gitster -- in commit cc77b99, 22 May 2015)

pull: remove --tags error in no merge candidates case

Since 441ed41 ("git pull --tags": error out with a better message., 2007-12-28, Git 1.5.4+), git pull --tags would print a different error message if git-fetch did not return any merge candidates:

It doesn't make sense to pull all tags; you probably meant:
       git fetch --tags

This is because at that time, git-fetch --tags would override any configured refspecs, and thus there would be no merge candidates. The error message was thus introduced to prevent confusion.

However, since c5a84e9 (fetch --tags: fetch tags in addition to other stuff, 2013-10-30, Git 1.9.0+), git fetch --tags would fetch tags in addition to any configured refspecs.
Hence, if any no merge candidates situation occurs, it is not because --tags was set. As such, this special error message is now irrelevant.

To prevent confusion, remove this error message.


With Git 2.11+ (Q4 2016) git fetch is quicker.

See commit 5827a03 (13 Oct 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 9fcd144, 26 Oct 2016)

fetch: use "quick" has_sha1_file for tag following

When fetching from a remote that has many tags that are irrelevant to branches we are following, we used to waste way too many cycles when checking if the object pointed at by a tag (that we are not going to fetch!) exists in our repository too carefully.

This patch teaches fetch to use HAS_SHA1_QUICK to sacrifice accuracy for speed, in cases where we might be racy with a simultaneous repack.

Here are results from the included perf script, which sets up a situation similar to the one described above:

Test            HEAD^               HEAD
----------------------------------------------------------
5550.4: fetch   11.21(10.42+0.78)   0.08(0.04+0.02) -99.3%

That applies only for a situation where:

  1. You have a lot of packs on the client side to make reprepare_packed_git() expensive (the most expensive part is finding duplicates in an unsorted list, which is currently quadratic).
  2. You need a large number of tag refs on the server side that are candidates for auto-following (i.e., that the client doesn't have). Each one triggers a re-read of the pack directory.
  3. Under normal circumstances, the client would auto-follow those tags and after one large fetch, (2) would no longer be true.
    But if those tags point to history which is disconnected from what the client otherwise fetches, then it will never auto-follow, and those candidates will impact it on every fetch.

Git 2.21 (Feb. 2019) seems to have introduced a regression when the config remote.origin.fetch is not the default one ('+refs/heads/*:refs/remotes/origin/*')

fatal: multiple updates for ref 'refs/tags/v1.0.0' not allowed

Git 2.24 (Q4 2019) adds another optimization.

See commit b7e2d8b (15 Sep 2019) by Masaya Suzuki (draftcode).
(Merged by Junio C Hamano -- gitster -- in commit 1d8b0df, 07 Oct 2019)

fetch: use oidset to keep the want OIDs for faster lookup

During git fetch, the client checks if the advertised tags' OIDs are already in the fetch request's want OID set.
This check is done in a linear scan.
For a repository that has a lot of refs, repeating this scan takes 15+ minutes.

In order to speed this up, create a oid_set for other refs' OIDs.

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

The fields of your object have in turn their fields, some of which do not implement Serializable. In your case the offending class is TransformGroup. How to solve it?

  • if the class is yours, make it Serializable
  • if the class is 3rd party, but you don't need it in the serialized form, mark the field as transient
  • if you need its data and it's third party, consider other means of serialization, like JSON, XML, BSON, MessagePack, etc. where you can get 3rd party objects serialized without modifying their definitions.

C++ templates that accept only certain types

The simple solution, which no one have mentioned yet, is to just ignore the problem. If I try to use an int as a template type in a function template that expects a container class such as vector or list, then I will get a compile error. Crude and simple, but it solves the problem. The compiler will try to use the type you specify, and if that fails, it generates a compile error.

The only problem with that is that the error messages you get are going to be tricky to read. It is nevertheless a very common way to do this. The standard library is full of function or class templates that expect certain behavior from the template type, and do nothing to check that the types used are valid.

If you want nicer error messages (or if you want to catch cases that wouldn't produce a compiler error, but still don't make sense) you can, depending on how complex you want to make it, use either Boost's static assert or the Boost concept_check library.

With an up-to-date compiler you have a built_in static_assert, which could be used instead.

SQL How to replace values of select return?

I saying that the case statement is wrong but this can be a good solution instead. If you choose to use the CASE statement, you have to make sure that at least one of the CASE condition is matched. Otherwise, you need to define an error handler to catch the error. Recall that you don’t have to do this with the IF statement.

SELECT if(hide = 0,FALSE,TRUE) col FROM tbl; #for BOOLEAN Value return

or

SELECT if(hide = 0,'FALSE','TRUE') col FROM tbl; #for string Value return

How to insert data to MySQL having auto incremented primary key?

I see three possibilities here that will help you insert into your table without making a complete mess but "specifying" a value for the AUTO_INCREMENT column, since you are supplying all the values you can do either one of the following options.

First approach (Supplying NULL):

INSERT INTO test.authors VALUES (
 NULL,'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
 '2012-01-03 12:50:59','198963','21','',
 '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
 '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
 '','rta=2.860000m=0%;80;100;0'
);

Second approach (Supplying '' {Simple quotes / apostrophes} although it will give you a warning):

INSERT INTO test.authors VALUES (
 '','1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
 '2012-01-03 12:50:59','198963','21','',
 '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
 '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
 '','rta=2.860000m=0%;80;100;0'
);

Third approach (Supplying default):

INSERT INTO test.authors VALUES (
 default,'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
 '2012-01-03 12:50:59','198963','21','',
 '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
 '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
 '','rta=2.860000m=0%;80;100;0'
);

Either one of these examples should suffice when inserting into that table as long as you include all the values in the same order as you defined them when creating the table.

Cannot use a leading ../ to exit above the top directory

I moved my project from "standard" hosting to Azure and get the same error when I try to open page with url-rewrite. I.e. rule is :

<add key="/iPod-eBook-Creator.html" value="/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR" />

try to open my_site/iPod-eBook-Creator.html and get this error (page my_site/Product/ProductDetail?PRODUCT_UID=IPOD_EBOOK_CREATOR can be opened without any problem).

I checked the fully site - never used .. to "level up"

How to link to a <div> on another page?

You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.

This is can done in this way:

add hash in the url of next_page : example.com#hashkey

$( document ).ready(function() {

  ##get hash code at next page
  var hashcode = window.location.hash;

  ## move page to any specific position of next page(let that is div with id "hashcode")
  $('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');

});

git: can't push (unpacker error) related to permission issues

This problem can also occur after Ubuntu upgrades that require a reboot.

If the file /var/run/reboot-required exists, do or schedule a restart.

MySQL, Check if a column exists in a table with SQL

@julio

Thanks for the SQL example. I tried the query and I think it needs a small alteration to get it working properly.

SELECT * 
FROM information_schema.COLUMNS 
WHERE 
    TABLE_SCHEMA = 'db_name' 
AND TABLE_NAME = 'table_name' 
AND COLUMN_NAME = 'column_name'

That worked for me.

Thanks!

Change HTML email body font type and size in VBA

FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :

strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"

How do I auto-submit an upload form when a file is selected?

Using jQuery:

_x000D_
_x000D_
$('#file').change(function() {_x000D_
  $('#target').submit();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="target" action="destination.html">_x000D_
  <input type="file" id="file" value="Go" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Laravel blade check empty foreach

I think you are trying to check whether the array is empty or not.You can do like this :

@if(!$result->isEmpty())
     // $result is not empty
@else
    // $result is empty
@endif

Reference isEmpty()

How to make EditText not editable through XML in Android?

Let your Edittext be

EditText editText;

editText.setKeyListener(null);

will work but it just not listening to keys.

User can see a cursor on the edittext.

You can try editText.setEnabled(false);

That means user cannot see the cursor. To simply say it will became TextView.

iPhone Debugging: How to resolve 'failed to get the task for process'?

I just changed my bundleIdentifier name, that seemed to do the trick.

How to select the rows with maximum values in each group with dplyr?

You can use top_n

df %>% group_by(A, B) %>% top_n(n=1)

This will rank by the last column (value) and return the top n=1 rows.

Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)

How to know function return type and argument types?

Yes it is.

In Python a function doesn't always have to return a variable of the same type (although your code will be more readable if your functions do always return the same type). That means that you can't specify a single return type for the function.

In the same way, the parameters don't always have to be the same type too.

Removing character in list of strings

Try this:

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print([s.strip('8') for s in lst]) # remove the 8 from the string borders
print([s.replace('8', '') for s in lst]) # remove all the 8s 

Django - filtering on foreign key properties

This has been possible since the queryset-refactor branch landed pre-1.0. Ticket 4088 exposed the problem. This should work:

Asset.objects.filter(
    desc__contains=filter,
    project__name__contains="Foo").order_by("desc")

The Django Many-to-one documentation has this and other examples of following Foreign Keys using the Model API.

Stop embedded youtube iframe?

For a Twitter Bootstrap modal/popup with a video inside, this worked for me:

_x000D_
_x000D_
$('.modal.stop-video-on-close').on('hidden.bs.modal', function(e) {_x000D_
  $('.video-to-stop', this).each(function() {_x000D_
    this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
_x000D_
<div id="vid" class="modal stop-video-on-close"_x000D_
  tabindex="-1" role="dialog" aria-labelledby="Title">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">_x000D_
          <span aria-hidden="true">&times;</span>_x000D_
        </button>_x000D_
        <h4 class="modal-title">Title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
       <iframe class="video-to-stop center-block"_x000D_
        src="https://www.youtube.com/embed/3q4LzDPK6ps?enablejsapi=1&rel=0"_x000D_
        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"_x000D_
        frameborder="0" allowfullscreen>_x000D_
       </iframe>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button class="btn btn-danger waves-effect waves-light"_x000D_
          data-dismiss="modal" type="button">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<button class="btn btn-success" data-toggle="modal"_x000D_
 data-target="#vid" type="button">Open video modal</button>
_x000D_
_x000D_
_x000D_

Based on Marco's answer, notice that I just needed to add the enablejsapi=1 parameter to the video URL (rel=0 is just for not displaying related videos at the end). The JS postMessage function is what does all the heavy lifting, it actually stops the video.

The snippet may not display the video due to request permissions, but in a regular browser this should work as of November of 2018.

What is the best way to determine a session variable is null or empty in C#?

That is pretty much how you do it. However, there is a shorter syntax you can use.

sSession = (string)Session["variable"] ?? "set this";

This is saying if the session variables is null, set sSession to "set this"

Can't specify the 'async' modifier on the 'Main' method of a console app

You can solve this with this simple construct:

class Program
{
    static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            // Do any async anything you need here without worry
        }).GetAwaiter().GetResult();
    }
}

That will put everything you do out on the ThreadPool where you'd want it (so other Tasks you start/await don't attempt to rejoin a Thread they shouldn't), and wait until everything's done before closing the Console app. No need for special loops or outside libs.

Edit: Incorporate Andrew's solution for uncaught Exceptions.

How to get first item from a java.util.Set?

There is no point in retrieving first element from a Set. If you have such kind of requirement use ArrayList instead of sets. Sets do not allow duplicates. They contain distinct elements.

How to build a query string for a URL in C#?

Just wanted to throw in my 2 cents:

public static class HttpClientExt
{
    public static Uri AddQueryParams(this Uri uri, string query)
    {
        var ub = new UriBuilder(uri);
        ub.Query = string.IsNullOrEmpty(uri.Query) ? query : string.Join("&", uri.Query.Substring(1), query);
        return ub.Uri;
    }

    public static Uri AddQueryParams(this Uri uri, IEnumerable<string> query)
    {
        return uri.AddQueryParams(string.Join("&", query));
    } 

    public static Uri AddQueryParams(this Uri uri, string key, string value)
    {
        return uri.AddQueryParams(string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value)));
    }

    public static Uri AddQueryParams(this Uri uri, params KeyValuePair<string,string>[] kvps)
    {
        return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
    }

    public static Uri AddQueryParams(this Uri uri, IDictionary<string, string> kvps)
    {
        return uri.AddQueryParams(kvps.Select(kvp => string.Join("=", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value))));
    }

    public static Uri AddQueryParams(this Uri uri, NameValueCollection nvc)
    {
        return uri.AddQueryParams(nvc.AllKeys.SelectMany(nvc.GetValues, (key, value) => string.Join("=", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))));
    }
}

The docs say that uri.Query will start with a ? if it's non-empty and you should trim it off if you're going to modify it.

Note that HttpUtility.UrlEncode is found in System.Web.

Usage:

var uri = new Uri("https://api.del.icio.us/v1/posts/suggest").AddQueryParam("url","http://stackoverflow.com")

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Duplicate and rename Xcode project & associated folders

For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.

Next, check that your current module is the correct renamed module and not the old one.

How to select an element inside "this" in jQuery?

$( this ).find( 'li.target' ).css("border", "3px double red");

or

$( this ).children( 'li.target' ).css("border", "3px double red");

Use children for immediate descendants, or find for deeper elements.

How to detect DIV's dimension changed?

A new standard for this is the Resize Observer api, available in Chrome 64.

_x000D_
_x000D_
function outputsize() {_x000D_
 width.value = textbox.offsetWidth_x000D_
 height.value = textbox.offsetHeight_x000D_
}_x000D_
outputsize()_x000D_
_x000D_
new ResizeObserver(outputsize).observe(textbox)
_x000D_
Width: <output id="width">0</output><br>_x000D_
Height: <output id="height">0</output><br>_x000D_
<textarea id="textbox">Resize me</textarea><br>
_x000D_
_x000D_
_x000D_

Resize Observer

Spec: https://wicg.github.io/ResizeObserver

Polyfills: https://github.com/WICG/ResizeObserver/issues/3

Firefox Issue: https://bugzil.la/1272409

Safari Issue: http://wkb.ug/157743

Current Support: http://caniuse.com/#feat=resizeobserver

Text in a flex container doesn't wrap in IE11

Add this to your code:

.child { width: 100%; }

We know that a block-level child is supposed to occupy the full width of the parent.

Chrome understands this.

IE11, for whatever reason, wants an explicit request.

Using flex-basis: 100% or flex: 1 also works.

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 400px;_x000D_
  border: 1px solid red;_x000D_
  align-items: center;_x000D_
}_x000D_
.child {_x000D_
  border: 1px solid blue;_x000D_
  width: calc(100% - 2px);       /* NEW; used calc to adjust for parent borders */_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">_x000D_
    Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    Lorem Ipsum is simply dummy text of the printing and typesetting industry_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note: Sometimes it will be necessary to sort through the various levels of the HTML structure to pinpoint which container gets the width: 100%. CSS wrap text not working in IE

How to select a div element in the code-behind page?

Give ID and attribute runat='server' as :

<div class="tab-pane active" id="portlet_tab1" runat="server">

//somecode Codebehind:

Access at code behind

    Control Test = Page.FindControl("portlet_tab1");
    Test.Style.Add("display", "none"); 

    or 

    portlet_tab1.Style.Add("display", "none"); 

Char array to hex string C++

Here is something:

char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

for( int i = data; i < data_length; ++i )
{
    char const byte = data[i];

    string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
    string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}

HTTP Error 404.3-Not Found in IIS 7.5

You should install IIS sub components from

Control Panel -> Programs and Features -> Turn Windows features on or off

Internet Information Services has subsection World Wide Web Services / Application Development Features

There you must check ASP.NET (.NET Extensibility, ISAPI Extensions, ISAPI Filters will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.

Run from cmd:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.

Also, look at this answer.

How do I append one string to another in Python?

Don't prematurely optimize. If you have no reason to believe there's a speed bottleneck caused by string concatenations then just stick with + and +=:

s  = 'foo'
s += 'bar'
s += 'baz'

That said, if you're aiming for something like Java's StringBuilder, the canonical Python idiom is to add items to a list and then use str.join to concatenate them all at the end:

l = []
l.append('foo')
l.append('bar')
l.append('baz')

s = ''.join(l)

Check if any ancestor has a class using jQuery

You can use parents method with specified .class selector and check if any of them matches it:

if ($elem.parents('.left').length != 0) {
    //someone has this class
}

I want to align the text in a <td> to the top

Use <td valign="top" style="width: 259px"> instead...

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

VBA: Convert Text to Number

For large datasets a faster solution is required.

Making use of 'Text to Columns' functionality provides a fast solution.

Example based on column F, starting range at 25 to LastRow

Sub ConvTxt2Nr()

Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long

Set sht = ThisWorkbook.Sheets("DumpDB")

LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row

Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)

SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True

End Sub

How to use glob() to find files recursively?

I needed a solution for python 2.x that works fast on large directories.
I endet up with this:

import subprocess
foundfiles= subprocess.check_output("ls src/*.c src/**/*.c", shell=True)
for foundfile in foundfiles.splitlines():
    print foundfile

Note that you might need some exception handling in case ls doesn't find any matching file.

Add number of days to a date

This one might be good

function addDayswithdate($date,$days){

    $date = strtotime("+".$days." days", strtotime($date));
    return  date("Y-m-d", $date);

}

How to change button text or link text in JavaScript?

Remove Quote. and use innerText instead of text

function toggleText(button_id) 
{                      //-----\/ 'button_id' - > button_id
   if (document.getElementById(button_id).innerText == "Lock") 
   {
       document.getElementById(button_id).innerText = "Unlock";
   }
   else 
   {
     document.getElementById(button_id).innerText = "Lock";
   }
}

Is it possible for UIStackView to scroll?

If you have a constraint to center the Stack View vertically inside the scroll view, just remove it.

DROP IF EXISTS VS DROP?

It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.

From SQL Server 2016+ you can use

DROP TABLE IF EXISTS dbo.Table

For SQL Server <2016 what I do is the following for a permanent table

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

Or this, for a temporary table

IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
  DROP TABLE #T; 

Bash if statement with multiple conditions throws an error

You can get some inspiration by reading an entrypoint.sh script written by the contributors from MySQL that checks whether the specified variables were set.

As the script shows, you can pipe them with -a, e.g.:

if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
    ...
fi

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

Yes there is one and it is inside the SQLServer management studio. Unlike the previous versions I think. Follow these simple steps.

1)Right click on a database in the Object explorer 2)Selected New Query from the popup menu 3)Query Analyzer will be opened.

Enjoy work.

Putting a password to a user in PhpMyAdmin in Wamp

my config.inc.php file in the phpmyadmin folder. Change username and password to the one you have set for your database.

    <?php
/*
 * This is needed for cookie based authentication to encrypt password in
 * cookie
 */
$cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

/*
 * Servers configuration
 */
$i = 0;

/*
 * First server
 */
$i++;

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'enter_username_here';
$cfg['Servers'][$i]['password'] = 'enter_password_here';
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';

/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';

/*
 * End of servers configuration
 */

?>

.NET unique object identifier

If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.

First, the official document does NOT guarantee that the GetHashCode() returns an unique identifier (see Object.GetHashCode Method ()):

You should not assume that equal hash codes imply object equality.

Second, assume you have a very small amount of objects so that GetHashCode() will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode() to always return 0. Then every object of C will get the same hash code. Unfortunately, Dictionary, HashTable and some other associative containers will make use this method:

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

So, this approach has great limitations.

And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.

I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;


namespace ObjectSet
{
    public interface IObjectSet
    {
        /// <summary> check the existence of an object. </summary>
        /// <returns> true if object is exist, false otherwise. </returns>
        bool IsExist(object obj);

        /// <summary> if the object is not in the set, add it in. else do nothing. </summary>
        /// <returns> true if successfully added, false otherwise. </returns>
        bool Add(object obj);
    }

    public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            return objectSet.TryGetValue(obj, out tryGetValue_out0);
        }

        public bool Add(object obj) {
            if (IsExist(obj)) {
                return false;
            } else {
                objectSet.Add(obj, null);
                return true;
            }
        }

        /// <summary> internal representation of the set. (only use the key) </summary>
        private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();

        /// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
        private static object tryGetValue_out0 = null;
    }

    [Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
    public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            bool firstTime;
            idGenerator.HasId(obj, out firstTime);
            return !firstTime;
        }

        public bool Add(object obj) {
            bool firstTime;
            idGenerator.GetId(obj, out firstTime);
            return firstTime;
        }


        /// <summary> internal representation of the set. </summary>
        private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
    }
}

In my test, the ObjectIDGenerator will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for loop.

Also, the benchmark result is that the ConditionalWeakTable implementation is 1.8x faster than the ObjectIDGenerator implementation.

How to generate a core dump in Linux on a segmentation fault?

As explained above the real question being asked here is how to enable core dumps on a system where they are not enabled. That question is answered here.

If you've come here hoping to learn how to generate a core dump for a hung process, the answer is

gcore <pid>

if gcore is not available on your system then

kill -ABRT <pid>

Don't use kill -SEGV as that will often invoke a signal handler making it harder to diagnose the stuck process

a href link for entire div in HTML/CSS

UPDATE 06/10/2014: using div's inside a's is semantically correct in HTML5.

You'll need to choose between the following scenarios:

<a href="http://google.com">
    <div>
        Hello world
    </div>
</a>

which is semantically incorrect, but it will work.

<div style="cursor: pointer;" onclick="window.location='http://google.com';">
    Hello world
</div>

which is semantically correct but it involves using JS.

<a href="http://google.com">
    <span style="display: block;">
        Hello world
    </span>
</a>

which is semantically correct and works as expected but is not a div any more.

delete all from table

This is deletes the table table_name.

Replace it with the name of the table, which shall be deleted.

DELETE FROM table_name;

How to pass parameter to function using in addEventListener?

No need to pass anything in. The function used for addEventListener will automatically have this bound to the current element. Simply use this in your function:

productLineSelect.addEventListener('change', getSelection, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Here's the fiddle: http://jsfiddle.net/dJ4Wm/


If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:

productLineSelect.addEventListener('change', function() {
    foo('bar');
}, false);

function foo(message) {
    alert(message);
}

Here's the fiddle: http://jsfiddle.net/t4Gun/


If you want to set the value of this manually, you can use the call method to call the function:

var self = this;
productLineSelect.addEventListener('change', function() {
    getSelection.call(self);
    // This'll set the `this` value inside of `getSelection` to `self`
}, false);

function getSelection() {
    var value = this.options[this.selectedIndex].value;
    alert(value);
}

Format telephone and credit card numbers in AngularJS

You will need to create custom form controls (as directives) for the phone number and the credit card. See section "Implementing custom form control (using ngModel)" on the forms page.

As Narretz already mentioned, Angular-ui's Mask directive should help get you started.

PowerShell Connect to FTP server and get files

The AlexFTPS library used in the question seems to be dead (was not updated since 2011).


With no external libraries

You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).

You have to implement that yourself:

  • List the remote directory
  • Iterate the entries, downloading files (and optionally recursing into subdirectories - listing them again, etc.)

Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest or WebClient). The .NET framework unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

Your options are:

  • If you know that the directory does not contain any subdirectories, use the ListDirectory method (NLST FTP command) and simply download all the "names" as files.
  • Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name".
  • You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
  • You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)
function DownloadFtpDirectory($url, $credentials, $localPath)
{
    $listRequest = [Net.WebRequest]::Create($url)
    $listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
    $listRequest.Credentials = $credentials

    $lines = New-Object System.Collections.ArrayList

    $listResponse = $listRequest.GetResponse()
    $listStream = $listResponse.GetResponseStream()
    $listReader = New-Object System.IO.StreamReader($listStream)
    while (!$listReader.EndOfStream)
    {
        $line = $listReader.ReadLine()
        $lines.Add($line) | Out-Null
    }
    $listReader.Dispose()
    $listStream.Dispose()
    $listResponse.Dispose()

    foreach ($line in $lines)
    {
        $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
        $name = $tokens[8]
        $permissions = $tokens[0]

        $localFilePath = Join-Path $localPath $name
        $fileUrl = ($url + $name)

        if ($permissions[0] -eq 'd')
        {
            if (!(Test-Path $localFilePath -PathType container))
            {
                Write-Host "Creating directory $localFilePath"
                New-Item $localFilePath -Type directory | Out-Null
            }

            DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
        }
        else
        {
            Write-Host "Downloading $fileUrl to $localFilePath"

            $downloadRequest = [Net.WebRequest]::Create($fileUrl)
            $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
            $downloadRequest.Credentials = $credentials

            $downloadResponse = $downloadRequest.GetResponse()
            $sourceStream = $downloadResponse.GetResponseStream()
            $targetStream = [System.IO.File]::Create($localFilePath)
            $buffer = New-Object byte[] 10240
            while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
            {
                $targetStream.Write($buffer, 0, $read);
            }
            $targetStream.Dispose()
            $sourceStream.Dispose()
            $downloadResponse.Dispose()
        }
    }
}

Use the function like:

$credentials = New-Object System.Net.NetworkCredential("user", "mypassword") 
$url = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory $url $credentials "C:\target\directory"

The code is translated from my C# example in C# Download all files and subdirectories through FTP.


Using 3rd party library

If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.

For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles:

# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "user"
    Password = "mypassword"
}

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    # Download files
    $session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}    

Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

The Session.GetFiles method is recursive by default.

(I'm the author of WinSCP)

Number format in excel: Showing % value without multiplying with 100

Here's a simple way:

=NUMBERVALUE( CONCAT(5.66,"%") )

Just concatenate a % symbol after the number. By itself, this output would be text, so we also tuck the CONCAT function inside the NUMBERVALUE function.

p.s., in old excel, you might need to type the full word "CONCATENATE"

Pass a variable to a PHP script running from the command line

You can use the following code to both work with the command line and a web browser. Put this code above your PHP code. It creates a $_GET variable for each command line parameter.

In your code you only need to check for $_GET variables then, not worrying about if the script is called from the web browser or command line.

if(isset($argv))
    foreach ($argv as $arg) {
        $e=explode("=",$arg);
        if(count($e)==2)
            $_GET[$e[0]]=$e[1];
        else
            $_GET[$e[0]]=0;
    }

pthread_join() and pthread_exit()

In pthread_exit, ret is an input parameter. You are simply passing the address of a variable to the function.

In pthread_join, ret is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL.

Long explanation:

In pthread_join, you get back the address passed to pthread_exit by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.

Iterate over object keys in node.js

For simple iteration of key/values, sometimes libraries like underscorejs can be your friend.

const _ = require('underscore');

_.each(a, function (value, key) {
    // handle
});

just for reference

Pandas: how to change all the values of a column?

As @DSM points out, you can do this more directly using the vectorised string methods:

df['Date'].str[-4:].astype(int)

Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)

An alternative slightly more flexible way, might be to use apply (or equivalently map) to do this:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer

The lambda function, is taking the input from the Date and converting it to a year.
You could (and perhaps should) write this more verbosely as:

def convert_to_year(date_in_some_format):
    date_as_string = str(date_in_some_format)  # cast to string
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)

Perhaps 'Year' is a better name for this column...

How can I selectively merge or pick changes from another branch in Git?

If you only need to merge a particular directory and leave everything else intact and yet preserve history, you could possibly try this... create a new target-branch off of the master before you experiment.

The steps below assume you have two branches target-branch and source-branch, and the directory dir-to-merge that you want to merge is in the source-branch. Also assume you have other directories like dir-to-retain in the target that you don't want to change and retain history. Also, assumes there are merge conflicts in the dir-to-merge.

git checkout target-branch
git merge --no-ff --no-commit -X theirs source-branch
# the option "-X theirs", will pick theirs when there is a conflict. 
# the options "--no--ff --no-commit" prevent a commit after a merge, and give you an opportunity to fix other directories you want to retain, before you commit this merge.

# the above, would have messed up the other directories that you want to retain.
# so you need to reset them for every directory that you want to retain.
git reset HEAD dir-to-retain
# verify everything and commit.

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

How to check a string against null in java?

With Java 7 you can use

if (Objects.equals(foo, null)) {
    ...
}

which will return true if both parameters are null.

Finding the handle to a WPF window

Well, instead of passing Application.Current.MainWindow, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handle and so on.

Excel SUMIF between dates

You haven't got your SUMIF in the correct order - it needs to be range, criteria, sum range. Try:

=SUMIF(A:A,">="&DATE(2012,1,1),B:B)

How can I read a text file in Android?

If you want to read file from sd card. Then following code might be helpful for you.

 StringBuilder text = new StringBuilder();
    try {
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"testFile.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));  
        String line;   
        while ((line = br.readLine()) != null) {
                    text.append(line);
                    Log.i("Test", "text : "+text+" : end");
                    text.append('\n');
                    } }
    catch (IOException e) {
        e.printStackTrace();                    

    }
    finally{
            br.close();
    }       
    TextView tv = (TextView)findViewById(R.id.amount);  

    tv.setText(text.toString()); ////Set the text to text view.
  }

    }

If you wan to read file from asset folder then

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:

InputStream is = getResources().openRawResource(R.raw.test);     

Good example of reading text file from res/raw folder

Putting text in top left corner of matplotlib plot

One solution would be to use the plt.legend function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc keyterm. More information can be found at this website but I've also included an example showing how to place a legend:

ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2) 

Note that because loc=2, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize, which will then make the legend smaller.

Force git stash to overwrite added files

To force git stash pop run this command

git stash show -p | git apply && git stash drop

Facebook OAuth "The domain of this URL isn't included in the app's domain"

on Magento 2 Social Login extension, you have to copy Valid OAuth redirect URIs from the panel and add the link to Valid OAuth Redirect URIs field in Client OAuth Settings page at developers.facebook.com

How to write super-fast file-streaming code in C#?

Using FileStream + StreamWriter I know it's possible to create massive files in little time (less than 1 min 30 seconds). I generate three files totaling 700+ megabytes from one file using that technique.

Your primary problem with the code you're using is that you are opening a file every time. That is creating file I/O overhead.

If you knew the names of the files you would be generating ahead of time, you could extract the File.OpenWrite into a separate method; it will increase the speed. Without seeing the code that determines how you are splitting the files, I don't think you can get much faster.

When a 'blur' event occurs, how can I find out which element focus went *to*?

As noted in this answer, you can check the value of document.activeElement. document is a global variable, so you don't have to do any magic to use it in your onBlur handler:

function myOnBlur(e) {
  if(document.activeElement ===
       document.getElementById('elementToCheckForFocus')) {
    // Focus went where we expected!
    // ...
  }
}

How to output only captured groups with sed?

run(s) of digits

This answer works with any count of digit groups. Example:

$ echo 'Num123that456are7899900contained0018166intext' \
   | sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'

123 456 7899900 0018166

Expanded answer.

Is there any way to tell sed to output only captured groups?

Yes. replace all text by the capture group:

$ echo 'Number 123 inside text' \
   | sed 's/[^0-9]*\([0-9]\{1,\}\)[^0-9]*/\1/'

123
s/[^0-9]*                           # several non-digits
         \([0-9]\{1,\}\)            # followed by one or more digits
                        [^0-9]*     # and followed by more non-digits.
                               /\1/ # gets replaced only by the digits.

Or with extended syntax (less backquotes and allow the use of +):

$ echo 'Number 123 in text' \
   | sed -E 's/[^0-9]*([0-9]+)[^0-9]*/\1/'

123

To avoid printing the original text when there is no number, use:

$ echo 'Number xxx in text' \
   | sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1/p'
  • (-n) Do not print the input by default.
  • (/p) print only if a replacement was done.

And to match several numbers (and also print them):

$ echo 'N 123 in 456 text' \
  | sed -En 's/[^0-9]*([0-9]+)[^0-9]*/\1 /gp'

123 456

That works for any count of digit runs:

$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" \
   | sed -En 's/[^0-9]*([0-9]{1,})[^0-9]*/\1 /gp'

123 456 7899900 0018166

Which is very similar to the grep command:

$ str='Test Num(s) 123 456 7899900 contained as0018166df in text'
$ echo "$str" | grep -Po '\d+'
123
456
7899900
0018166

About \d

and pattern: /([\d]+)/

Sed does not recognize the '\d' (shortcut) syntax. The ascii equivalent used above [0-9] is not exactly equivalent. The only alternative solution is to use a character class: '[[:digit:]]`.

The selected answer use such "character classes" to build a solution:

$ str='This is a sample 123 text and some 987 numbers'
$ echo "$str" | sed -rn 's/[^[:digit:]]*([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)[^[:digit:]]*/\1 \2/p'

That solution only works for (exactly) two runs of digits.

Of course, as the answer is being executed inside the shell, we can define a couple of variables to make such answer shorter:

$ str='This is a sample 123 text and some 987 numbers'
$ d=[[:digit:]]     D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D+($d+)$D*/\1 \2/p"

But, as has been already explained, using a s/…/…/gp command is better:

$ str='This is 75577 a sam33ple 123 text and some 987 numbers'
$ d=[[:digit:]]     D=[^[:digit:]]
$ echo "$str" | sed -rn "s/$D*($d+)$D*/\1 /gp"
75577 33 123 987

That will cover both repeated runs of digits and writing a short(er) command.

Default value of function parameter

On thing to remember here is that the default param must be the last param in the function definition.

Following code will not compile:

void fun(int first, int second = 10, int third);

Following code will compile:

void fun(int first, int second, int third = 10);

Using Spring 3 autowire in a standalone Java application

For Spring 4, using Spring Boot we can have the following example without using the anti-pattern of getting the Bean from the ApplicationContext directly:

package com.yourproject;

@SpringBootApplication
public class TestBed implements CommandLineRunner {

    private MyService myService;

    @Autowired
    public TestBed(MyService myService){
        this.myService = myService;
    }

    public static void main(String... args) {
        SpringApplication.run(TestBed.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("myService: " + MyService );
    }

}

@Service 
public class MyService{
    public String getSomething() {
        return "something";
    }
}

Make sure that all your injected services are under com.yourproject or its subpackages.

What is Model in ModelAndView from Spring MVC?

It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.

So ...

   new ModelAndView(view, name, value);

is equivalent to:

   Map model = ...
   model.put(name, value);
   new ModelAndView(view, model);

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How do you force a makefile to rebuild a target

As abernier pointed out, there is a recommended solution in the GNU make manual, which uses a 'fake' target to force rebuilding of a target:

clean: FORCE
        rm $(objects)
FORCE: ; 

This will run clean, regardless of any other dependencies.

I added the semicolon to the solution from the manual, otherwise an empty line is required.

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

Okay: This is what I did now and it's solved:

My httpd-vhosts.conf looks like this now:

<VirtualHost dropbox.local:80>
    DocumentRoot "E:/Documenten/Dropbox/Dropbox/dummy-htdocs"
    ServerName dropbox.local
    ErrorLog "logs/dropbox.local-error.log"
    CustomLog "logs/dropbox.local-access.log" combined
    <Directory "E:/Documenten/Dropbox/Dropbox/dummy-htdocs">
        # AllowOverride All      # Deprecated
        # Order Allow,Deny       # Deprecated
        # Allow from all         # Deprecated

        # --New way of doing it
        Require all granted    
    </Directory>
</VirtualHost>

First, I saw that it's necessary to have set the <Directory xx:xx> options. So I put the <Directory > [..] </Directory>-part INSIDE the <VirtualHost > [..] </VirtualHost>. After that, I added AllowOverride AuthConfig Indexes to the <Directory> options.

Now http://localhost also points to the dropbox-virtualhost. So I added dropbox.local to <VirtualHost *:80> which makes it as <VirtualHost dropbox.local:80>

FINALLY it works :D!

I'm a happy man! :) :)

I hope someone else can use this information.

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));  //copy

In this case, list1 is of type ArrayList.

List<Integer> list2 = Arrays.asList(ia);

Here, the list is returned as a List view, meaning it has only the methods attached to that interface. Hence why some methods are not allowed on list2.

ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));

Here, you ARE creating a new ArrayList. You're simply passing it a value in the constructor. This is not an example of casting. In casting, it might look more like this:

ArrayList list1 = (ArrayList)Arrays.asList(ia);

Cookies vs. sessions

Sessions allow you to store away individual pieces of information just like with cookies, but the data gets stored on the server instead of the client.

How can I export Excel files using JavaScript?

There is an interesting project on github called Excel Builder (.js) that offers a client-side way of downloading Excel xlsx files and includes options for formatting the Excel spreadsheet.
https://github.com/stephenliberty/excel-builder.js

You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful.

Another github project with less Excel options but less worries about Excel compatibility issues can be found here: ExcellentExport.js
https://github.com/jmaister/excellentexport

If you are using AngularJS, there is ng-csv:
a "Simple directive that turns arrays and objects into downloadable CSV files".

SUM OVER PARTITION BY

remove partition by and add group by clause,

SELECT BrandId
      ,SUM(ICount) totalSum
  FROM Table 
WHERE DateId  = 20130618
GROUP BY BrandId

How to comment multiple lines in Visual Studio Code?

CTRL + / comment / uncomment multiple lines of code

Ctrl+k+u for upper case latter

ctrl+k+l for lower case latter

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

How to loop and render elements in React-native?

You would usually use map for that kind of thing.

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);

(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)

As a side, I would use an object instead of an array. I find it looks nicer:

initialArr = [
  {
    id: 1,
    color: "blue",
    text: "text1"
  },
  {
    id: 2,
    color: "red",
    text: "text2"
  },
];

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);

How to convert a set to a list in python?

Simply type:

list(my_set)

This will turn a set in the form {'1','2'} into a list in the form ['1','2'].

os.path.dirname(__file__) returns empty

Because os.path.abspath = os.path.dirname + os.path.basename does not hold. we rather have

os.path.dirname(filename) + os.path.basename(filename) == filename

Both dirname() and basename() only split the passed filename into components without taking into account the current directory. If you want to also consider the current directory, you have to do so explicitly.

To get the dirname of the absolute path, use

os.path.dirname(os.path.abspath(__file__))

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

How do I retrieve query parameters in Spring Boot?

While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.

@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) { 
    if( itemid.isPresent()){
         Item i = itemDao.findOne(itemid.get());              
         return i;
     } else ....
}

Limit Decimal Places in Android EditText

Here is my solution:

     yourEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            NumberFormat formatter = new DecimalFormat("#.##");
            double doubleVal = Double.parseDouble(s.toString());
            yourEditText.setText(formatter.format(doubleVal));
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {}

        @Override
        public void afterTextChanged(Editable s) {}
    });

If the user enters a number with more than two numbers after the decimal point, it will be automatically corrected.

I hope I have helped!

commands not found on zsh

I fixed the issue by opening the terminal preference general tab and changing the Command (complete path) to /bin/bash to default and then editing the ~/.zshrc file.

enter image description here

export PATH="all your path inside the quotes"

...without any whitespace between the PATH=" and save the file.

enter image description here

After saving the file, change the /bin/zsh in your command or select default enter image description here

...and restart terminal and you should have your zsh shell working again!

How to remove the querystring and get only the url?

Assuming you still want to get the URL without the query args (if they are not set), just use a shorthand if statement to check with strpos:

$request_uri = strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $_SERVER['REQUEST_URI'];

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

Using the "start" command with parameters passed to the started program

You can use quotes by using the [/D"Path"] use /D only for specifying the path and not the path+program. It appears that all code on the same line that follows goes back to normal meaning you don't need to separate path and file.

    start  /D "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

or:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE

will start IE with default web page.

    start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE www.bing.com

starts with Bing, but does not reset your home page.

/D stands for "directory" and using quotes is OK!

WRONG EXAMPLE:

    start  /D "TITLE" "C:\Program Files\Internet Explorer\IEXPLORE.EXE"

gives:

ERROR "The current directory is invalid."

/D must only be followed by a directory path. Then space and the batchfile or program you wish to start/run

Tested and works under XP but windows Vista/7/8 may need some adjustments to UAC.

-Mrbios

Convert seconds value to hours minutes seconds?

I like to keep things simple therefore:

    int tot_seconds = 5000;
    int hours = tot_seconds / 3600;
    int minutes = (tot_seconds % 3600) / 60;
    int seconds = tot_seconds % 60;

    String timeString = String.format("%02d Hour %02d Minutes %02d Seconds ", hours, minutes, seconds);

    System.out.println(timeString);

The result will be: 01 Hour 23 Minutes 20 Seconds

What is the difference between Class.getResource() and ClassLoader.getResource()?

I tried reading from input1.txt which was inside one of my packages together with the class which was trying to read it.

The following works:

String fileName = FileTransferClient.class.getResource("input1.txt").getPath();

System.out.println(fileName);

BufferedReader bufferedTextIn = new BufferedReader(new FileReader(fileName));

The most important part was to call getPath() if you want the correct path name in String format. DO NOT USE toString() because it will add some extra formatting text which will TOTALLY MESS UP the fileName (you can try it and see the print out).

Spent 2 hours debugging this... :(

How to monitor SQL Server table changes by using c#?

This isn't exactly a notification but in the title you say monitor and this can fit that scenario.

Using the SQL Server timestamp column can allow you to easily see any changes (that still persist) between queries.

The SQL Server timestamp column type is badly named in my opinion as it is not related to time at all, it's a database wide value that auto increments on any insert or update. You can select Max(timestamp) in a table you are after or return the timestamp from the row you just inserted then just select where timestamp > storedTimestamp, this will give you all the results that have been updated or inserted between those times.

As it's a database wide value too you can use your stored timestamp to check any table has had data written to it since you last checked/updated your stored timestamp.

Rotate a div using javascript

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

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

Basically, my code looks like this...

Run Code Snippet

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

How do I make a WPF TextBlock show my text on multiple lines?

Use the property TextWrapping of the TextBlock element:

<TextBlock Text="StackOverflow Forum"
           Width="100"
           TextWrapping="WrapWithOverflow"/>

Java Class that implements Map and keeps insertion order?

I suggest a LinkedHashMap or a TreeMap. A LinkedHashMap keeps the keys in the order they were inserted, while a TreeMap is kept sorted via a Comparator or the natural Comparable ordering of the elements.

Since it doesn't have to keep the elements sorted, LinkedHashMap should be faster for most cases; TreeMap has O(log n) performance for containsKey, get, put, and remove, according to the Javadocs, while LinkedHashMap is O(1) for each.

If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap or SortedMap. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.

Invoking Java main method with parameters from Eclipse

If have spaces within your string argument, do the following:

Run > Run Configurations > Java Application > Arguments > Program arguments

  1. Enclose your string argument with quotes
  2. Separate each argument by space or new line

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

round() for float in C++

Function double round(double) with the use of the modf function:

double round(double x)
{
    using namespace std;

    if ((numeric_limits<double>::max() - 0.5) <= x)
        return numeric_limits<double>::max();

    if ((-1*std::numeric_limits<double>::max() + 0.5) > x)
        return (-1*std::numeric_limits<double>::max());

    double intpart;
    double fractpart = modf(x, &intpart);

    if (fractpart >= 0.5)
        return (intpart + 1);
    else if (fractpart >= -0.5)
        return intpart;
    else
        return (intpart - 1);
    }

To be compile clean, includes "math.h" and "limits" are necessary. The function works according to a following rounding schema:

  • round of 5.0 is 5.0
  • round of 3.8 is 4.0
  • round of 2.3 is 2.0
  • round of 1.5 is 2.0
  • round of 0.501 is 1.0
  • round of 0.5 is 1.0
  • round of 0.499 is 0.0
  • round of 0.01 is 0.0
  • round of 0.0 is 0.0
  • round of -0.01 is -0.0
  • round of -0.499 is -0.0
  • round of -0.5 is -0.0
  • round of -0.501 is -1.0
  • round of -1.5 is -1.0
  • round of -2.3 is -2.0
  • round of -3.8 is -4.0
  • round of -5.0 is -5.0

How to ping an IP address

Check your connectivity. On my Computer this prints REACHABLE for both IP's:

Sending Ping Request to 127.0.0.1
Host is reachable
Sending Ping Request to 173.194.32.38
Host is reachable

EDIT:

You could try modifying the code to use getByAddress() to obtain the address:

public static void main(String[] args) throws UnknownHostException, IOException {
    InetAddress inet;

    inet = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
    System.out.println("Sending Ping Request to " + inet);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");

    inet = InetAddress.getByAddress(new byte[] { (byte) 173, (byte) 194, 32, 38 });
    System.out.println("Sending Ping Request to " + inet);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
}

The getByName() methods may attempt some kind of reverse DNS lookup which may not be possible on your machine, getByAddress() might bypass that.

How to retrieve the LoaderException property?

catch (ReflectionTypeLoadException ex)
{        
    foreach (var item in ex.LoaderExceptions)
    {
          MessageBox.Show(item.Message);                    
    }
}

I'm sorry for resurrecting an old thread, but wanted to post a different solution to pull the loader exception (Using the actual ReflectionTypeLoadException) for anybody else to come across this.

How do I execute a stored procedure once for each row returned by query?

Use a table variable or a temporary table.

As has been mentioned before, a cursor is a last resort. Mostly because it uses lots of resources, issues locks and might be a sign you're just not understanding how to use SQL properly.

Side note: I once came across a solution that used cursors to update rows in a table. After some scrutiny, it turned out the whole thing could be replaced with a single UPDATE command. However, in this case, where a stored procedure should be executed, a single SQL-command won't work.

Create a table variable like this (if you're working with lots of data or are short on memory, use a temporary table instead):

DECLARE @menus AS TABLE (
    id INT IDENTITY(1,1),
    parent NVARCHAR(128),
    child NVARCHAR(128));

The id is important.

Replace parent and child with some good data, e.g. relevant identifiers or the whole set of data to be operated on.

Insert data in the table, e.g.:

INSERT INTO @menus (parent, child) 
  VALUES ('Some name',  'Child name');
...
INSERT INTO @menus (parent,child) 
  VALUES ('Some other name', 'Some other child name');

Declare some variables:

DECLARE @id INT = 1;
DECLARE @parentName NVARCHAR(128);
DECLARE @childName NVARCHAR(128);

And finally, create a while loop over the data in the table:

WHILE @id IS NOT NULL
BEGIN
    SELECT @parentName = parent,
           @childName = child 
        FROM @menus WHERE id = @id;

    EXEC myProcedure @parent=@parentName, @child=@childName;

    SELECT @id = MIN(id) FROM @menus WHERE id > @id;
END

The first select fetches data from the temporary table. The second select updates the @id. MIN returns null if no rows were selected.

An alternative approach is to loop while the table has rows, SELECT TOP 1 and remove the selected row from the temp table:

WHILE EXISTS(SELECT 1 FROM @menuIDs) 
BEGIN
    SELECT TOP 1 @menuID = menuID FROM @menuIDs;

    EXEC myProcedure @menuID=@menuID;

    DELETE FROM @menuIDs WHERE menuID = @menuID;
END;

How to include jQuery in ASP.Net project?

You might be looking for this Microsoft Ajax Content Delivery Network So you could just add

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

To your aspx page.

HttpServletRequest to complete URL

You can use filter .

@Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
            HttpServletRequest test1=    (HttpServletRequest) arg0;

         test1.getRequestURL()); it gives  http://localhost:8081/applicationName/menu/index.action
         test1.getRequestURI()); it gives applicationName/menu/index.action
         String pathname = test1.getServletPath()); it gives //menu/index.action


        if(pathname.equals("//menu/index.action")){ 
            arg2.doFilter(arg0, arg1); // call to urs servlet or frameowrk managed controller method


            // in resposne 
           HttpServletResponse httpResp = (HttpServletResponse) arg1;
           RequestDispatcher rd = arg0.getRequestDispatcher("another.jsp");     
           rd.forward(arg0, arg1);





    }

donot forget to put <dispatcher>FORWARD</dispatcher> in filter mapping in web.xml

html "data-" attribute as javascript parameter

If you are using jQuery you can easily fetch the data attributes by

$(this).data("id") or $(event.target).data("id")

Bootstrap css hides portion of container below navbar navbar-fixed-top

i solved it using jquery

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function(e) {_x000D_
   var h = $('nav').height() + 20;_x000D_
   $('body').animate({ paddingTop: h });_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

Mockito - NullpointerException when stubbing Method

Corner case:
If you're using Scala and you try to create an any matcher on a value class, you'll get an unhelpful NPE.

So given case class ValueClass(value: Int) extends AnyVal, what you want to do is ValueClass(anyInt) instead of any[ValueClass]

when(mock.someMethod(ValueClass(anyInt))).thenAnswer {
   ...
   val v  = ValueClass(invocation.getArguments()(0).asInstanceOf[Int])
   ...
}

This other SO question is more specifically about that, but you'd miss it when you don't know the issue is with value classes.

Using request.setAttribute in a JSP page

If you want your requests to persists try this:

example: on your JSP or servlet page

request.getSession().setAttribute("SUBFAMILY", subFam);

and on any receiving page use the below lines to retrieve your session and data:

SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");

How to show soft-keyboard when edittext is focused

I discovered a strange behaviour, since in one of my apps, the soft keyboard was automatically showing on entering the activity (there is an editText.requestFocus() in onCreate).

On digging further, I discovered that this was because there is a ScrollView around the layout. If I remove the ScrollView, the behaviour is as described in the original problem statement: only on clicking the already focused editText does the soft keyboard show up.

If it doesn't work for you, try putting in a ScrollView -- it's harmless anyway.

Android WebView style background-color:transparent ignored on android 2.2

If webview is scrollable:

  1. Add this to the Manifest:

    android:hardwareAccelerated="false"
    

OR

  1. Add the following to WebView in the layout:

    android:background="@android:color/transparent"
    android:layerType="software"
    
  2. Add the following to the parents scroll view:

    android:layerType="software"
    

How to create a box when mouse over text in pure CSS?

You can easily make this CSS Tool Tip through simple code :-

    <!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
a.info{
    position:relative; /*this is the key*/
    color:#000;
    top:100px;
    left:50px;
    text-decoration:none;
    text-align:center;
  }



a.info span{display: none}

a.info:hover span{ /*the span will display just on :hover state*/
    display:block;
    position:absolute;
    top:-60px;
    width:15em;
    border:5px solid #0cf;
    background-color:#cff; color:#000;
    text-align: center;
    padding:10px;
  }

  a.info:hover span:after{ /*the span will display just on :hover state*/
    content:'';
    position:absolute;
    bottom:-11px;
    width:10px;
    height:10px;
    border-bottom:5px solid #0cf;
    border-right:5px solid #0cf;
    background:#cff;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    transform:rotate(45deg);
  }


</style>
</head>
<body>
<a href="#" class="info">Shailender Arora <span>TOOLTIP</span></a>
  </div>
</body>
</html>

http://jsbin.com/ebucoz/25/edit

how to release localhost from Error: listen EADDRINUSE

In window, please execute this command:

taskkill /F /PID 1952

Debugging WebSocket in Google Chrome

Short answer for Chrome Version 29 and up:

  1. Open debugger, go to the tab "Network"
  2. Load page with websocket
  3. Click on the websocket request with upgrade response from server
  4. Select the tab "Frames" to see websocket frames
  5. Click on the websocket request again to refresh frames

Sending Windows key using SendKeys

Alt+F4 is working only in brackets

SendKeys.SendWait("(%{F4})");

Convert String to Uri

You can use the parse static method from Uri

//...
import android.net.Uri;
//...

Uri myUri = Uri.parse("http://stackoverflow.com")

Spring Data and Native Query with pagination

I could successfully integrate Pagination in

spring-data-jpa-2.1.6

as follows.

@Query(
 value = “SELECT * FROM Users”, 
 countQuery = “SELECT count(*) FROM Users”, 
 nativeQuery = true)
Page<User> findAllUsersWithPagination(Pageable pageable);

AngularJS - Access to child scope

You can try this:

$scope.child = {} //declare it in parent controller (scope)

then in child controller (scope) add:

var parentScope = $scope.$parent;
parentScope.child = $scope;

Now the parent has access to the child's scope.

How do I use select with date condition?

if you do not want to be bothered by the date format, you could compare the column with the general date format, for example

select * From table where cast (RegistrationDate as date) between '20161201' and '20161220'

make sure the date is in DATE format, otherwise cast (col as DATE)

How to maintain page scroll position after a jquery event is carried out?

$('html,body').animate({
  scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

check this image link for all steps https://drive.google.com/open?id=0B0-Ll2y6vo_sQ29hYndnbGZVZms

STEP1: I created a field of type varbinary in table

STEP2: I created a stored procedure to accept a parameter of type sql_variant

STEP3: In my front end asp.net page, I created a sql data source parameter of object type

        <tr>
        <td>
            UPLOAD DOCUMENT</td>
        <td>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
            <asp:SqlDataSource ID="sqldsFileUploadConn" runat="server" 
                ConnectionString="<%$ ConnectionStrings: %>" 
                InsertCommand="ph_SaveDocument"     
               InsertCommandType="StoredProcedure">
                <InsertParameters>
                    <asp:Parameter Name="DocBinaryForm" Type="Object" />
                </InsertParameters>

             </asp:SqlDataSource>
        </td>
        <td>
            &nbsp;</td>
    </tr>

STEP 4: In my code behind, I try to upload the FileBytes from FileUpload Control via this stored procedure call using a sql data source control

      Dim filebytes As Object
      filebytes = FileUpload1.FileBytes()
      sqldsFileUploadConn.InsertParameters("DocBinaryForm").DefaultValue = filebytes.ToString
      Dim uploadstatus As Int16 = sqldsFileUploadConn.Insert()

               ' ... code continues ... '

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

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

On a Windows machine I was able to log to to ssh from git bash with
ssh vagrant@VAGRANT_SERVER_IP without providing a password

Using Bitvise SSH client on window
Server host: VAGRANT_SERVER_IP
Server port: 22
Username: vagrant
Password: vagrant

How to split csv whose columns may contain ,

You could split on all commas that do have an even number of quotes following them.

You would also like to view at the specf for CSV format about handling comma's.

Useful Link : C# Regex Split - commas outside quotes

Convert a list of characters into a string

This may be the fastest way:

>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'

Updating a local repository with changes from a GitHub repository

This question is very general and there are a couple of assumptions I'll make to simplify it a bit. We'll assume that you want to update your master branch.

If you haven't made any changes locally, you can use git pull to bring down any new commits and add them to your master.

git pull origin master

If you have made changes, and you want to avoid adding a new merge commit, use git pull --rebase.

git pull --rebase origin master

git pull --rebase will work even if you haven't made changes and is probably your best call.

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

On 2017-01-25 Apple released a technical Q&A regarding this error:

Apple Technical Q&A QA1941

Handling “The network connection was lost” Errors

A: NSURLErrorNetworkConnectionLost is error -1005 in the NSURLErrorDomain error domain, and is displayed to users as “The network connection was lost”. This error means that the underlying TCP connection that’s carrying the HTTP request disconnected while the HTTP request was in progress (see below for more information about this). In some circumstances NSURLSession may retry such requests automatically (specifically, if the request is idempotent) but in other circumstances that’s not allowed by the HTTP standards.

https://developer.apple.com/library/archive/qa/qa1941/_index.html#//apple_ref/doc/uid/DTS40017602

TransactionRequiredException Executing an update/delete query

The same exception occurred to me in a somewhat different situation. Since I've been searching here for an answer, maybe it'll help somebody.

I my case the exception has been happening because I called the (properly annotated) @Transactional method from a SERVICE CONSTRUCTOR... Since my idea was simply to make this method run at the start, I annotated it as following, and stopped calling in a wrong way. Exception is gone, and code is better :)

@EventListener(ContextRefreshedEvent.class)
@Transactional
public void methodName() {...}

@Transactional import: import org.springframework.transaction.annotation.Transactional;

Why can't I have abstract static methods in C#?

This question is 12 years old but it still needs to be given a better answer. As few noted in the comments and contrarily to what all answers pretend it would certainly make sense to have static abstract methods in C#. As philosopher Daniel Dennett put it, a failure of imagination is not an insight into necessity. There is a common mistake in not realizing that C# is not only an OOP language. A pure OOP perspective on a given concept leads to a restricted and in the current case misguided examination. Polymorphism is not only about subtying polymorphism: it also includes parametric polymorphism (aka generic programming) and C# has been supporting this for a long time now. Within this additional paradigm, abstract classes (and most types) are not only used to type instances. They can also be used as bounds for generic parameters; something that has been understood by users of certain languages (like for example Haskell, but also more recently Scala, Rust or Swift) for years.

In this context you may want to do something like this:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = TAnimal.ScientificName; // abstract static property
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

And here the capacity to express static members that can be specialized by subclasses totally makes sense!

Unfortunately C# does not allow abstract static members but I'd like to propose a pattern that can emulate them reasonably well. This pattern is not perfect (it imposes some restrictions on inheritance) but as far as I can tell it is typesafe.

The main idea is to associate an abstract companion class (here SpeciesFor<TAnimal>) to the one that should contain abstract members (here Animal):

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal
{
    public static SpeciesFor<TAnimal> Instance { get { … } }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

public abstract class Animal { … }

Now we would like to make this work:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = SpeciesFor<TAnimal>.Instance.ScientificName;
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

Of course we have two problems to solve:

  1. How do we allow and force an implementer of a subclass of Animal to associate a specific instance of SpeciesFor<TAnimal> to this subclass?
  2. How does the property SpeciesFor<TAnimal>.Instance retrieve this information?

Here is how we can solve 1:

public abstract class Animal<TSelf> where TSelf : Animal<TSelf>
{
    private Animal(…) {}
    
    public abstract class OfSpecies<TSpecies> : Animal<TSelf>
        where TSpecies : SpeciesFor<TSelf>, new()
    {
        protected OfSpecies(…) : base(…) { }
    }
    
    …
}

By making the constructor of Animal<TSelf> private we make sure that all its subclasses are also subclasses of inner class Animal<TSelf>.OfSpecies<TSpecies>. So these subclasses must specify a TSpecies type that has a new() bound.

For 2 we can provide the following implementation:

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal<TAnimal>
{
    private static SpeciesFor<TAnimal> _instance;

    public static SpeciesFor<TAnimal> Instance => _instance ??= MakeInstance();

    private static SpeciesFor<TAnimal> MakeInstance()
    {
        Type t = typeof(TAnimal);
        while (true)
        {
            if (t.IsConstructedGenericType
                    && t.GetGenericTypeDefinition() == typeof(Animal<>.OfSpecies<>))
                return (SpeciesFor<TAnimal>)Activator.CreateInstance(t.GenericTypeArguments[1]);
            t = t.BaseType;
            if (t == null)
                throw new InvalidProgramException();
        }
    }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

How can we be sure that the reflection code inside MakeInstance() never throws? As we've already said, almost all classes within the hierarchy of Animal<TSelf> are also subclasses of Animal<TSelf>.OfSpecies<TSpecies>. So we know that for these classes a specific TSpecies must be provided. This type is also necessarily constructible thanks to constraint : new(). But this still leaves abstract types like Animal<Something> that have no associated species. Now we can convince ourself that the curiously recurring template pattern where TAnimal : Animal<TAnimal> makes it impossible to write SpeciesFor<Animal<Something>>.Instance as type Animal<Something> is never a subtype of Animal<Animal<Something>>.

Et voilà:

public class CatSpecies : SpeciesFor<Cat>
{
    // overriden "static" members

    public override string ScientificName => "Felis catus";
    public override Cat CreateInVivoFromDnaTrappedInAmber() { … }
    public override Cat Clone(Cat a) { … }
    public override Cat Breed(Cat a1, Cat a2) { … }
}

public class Cat : Animal<Cat>.OfSpecies<CatSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class DogSpecies : SpeciesFor<Dog>
{
    // overriden "static" members

    public override string ScientificName => "Canis lupus familiaris";
    public override Dog CreateInVivoFromDnaTrappedInAmber() { … }
    public override Dog Clone(Dog a) { … }
    public override Dog Breed(Dog a1, Dog a2) { … }
}

public class Dog : Animal<Dog>.OfSpecies<DogSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class Program
{
    public static void Main()
    {
        ConductCrazyScientificExperimentsWith<Cat>();
        ConductCrazyScientificExperimentsWith<Dog>();
        ConductCrazyScientificExperimentsWith<Tyranosaurus>();
        ConductCrazyScientificExperimentsWith<Wyvern>();
    }
    
    public static void ConductCrazyScientificExperimentsWith<TAnimal>()
        where TAnimal : Animal<TAnimal>
    {
        // Look Ma! No animal instance polymorphism!
        
        TAnimal a2039 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a2988 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a0400 = SpeciesFor<TAnimal>.Instance.Clone(a2988);
        TAnimal a9477 = SpeciesFor<TAnimal>.Instance.Breed(a0400, a2039);
        TAnimal a9404 = SpeciesFor<TAnimal>.Instance.Breed(a2988, a9477);
        
        Console.WriteLine(
            "The confederation of mad scientists is happy to announce the birth " +
            $"of {a9404.CuteName}, our new {SpeciesFor<TAnimal>.Instance.ScientificName}.");
    }
}

A limitation of this pattern is that it is not possible (as far as I can tell) to extend the class hierarchy in a satifying manner. For example we cannot introduce an intermediary Mammal class associated to a MammalClass companion. Another is that it does not work for static members in interfaces which would be more flexible than abstract classes.

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How do I correct this Illegal String Offset?

I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.

How do I run a docker instance from a DockerFile?

While other answers were usable, this really helped me, so I am putting it also here.

From the documentation:

Instead of specifying a context, you can pass a single Dockerfile in the URL or pipe the file in via STDIN. To pipe a Dockerfile from STDIN:

$ docker build - < Dockerfile

With Powershell on Windows, you can run:

Get-Content Dockerfile | docker build -

When the build is done, run command:

docker image ls

You will see something like this:

REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
<none>                     <none>              123456789        39 seconds ago      422MB

Copy your actual IMAGE ID and then run

docker run 123456789

Where the number at the end is the actual Image ID from previous step

If you do not want to remember the image id, you can tag your image by

docker tag 123456789 pavel/pavel-build

Which will tag your image as pavel/pavel-build

Is it better to return null or empty collection?

I would argue that null isn't the same thing as an empty collection and you should choose which one best represents what you're returning. In most cases null is nothing (except in SQL). An empty collection is something, albeit an empty something.

If you have have to choose one or the other, I would say that you should tend towards an empty collection rather than null. But there are times when an empty collection isn't the same thing as a null value.

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

How to get an HTML element's style values in javascript?

In jQuery, you can do alert($("#theid").css("width")).

-- if you haven't taken a look at jQuery, I highly recommend it; it makes many simple javascript tasks effortless.

Update

for the record, this post is 5 years old. The web has developed, moved on, etc. There are ways to do this with Plain Old Javascript, which is better.

What is the largest TCP/IP network port number allowable for IPv4?

The largest port number is an unsigned short 2^16-1: 65535

A registered port is one assigned by the Internet Corporation for Assigned Names and Numbers (ICANN) to a certain use. Each registered port is in the range 1024–49151.

Since 21 March 2001 the registry agency is ICANN; before that time it was IANA.

Ports with numbers lower than those of the registered ports are called well known ports; port with numbers greater than those of the registered ports are called dynamic and/or private ports.

Wikipedia : Registered Ports

remove legend title in ggplot

This works too and also demonstrates how to change the legend title:

ggplot(df, aes(x, y, colour=g)) +
  geom_line(stat="identity") + 
  theme(legend.position="bottom") +
  scale_color_discrete(name="")

How to unset a JavaScript variable?

You cannot delete a variable if you declared it (with var x;) at the time of first use. However, if your variable x first appeared in the script without a declaration, then you can use the delete operator (delete x;) and your variable will be deleted, very similar to deleting an element of an array or deleting a property of an object.

convert a JavaScript string variable to decimal/money

It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.

What do >> and << mean in Python?

These are bitwise shift operators.

Quoting from the docs:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y

Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.

Get the size of the screen, current web page and browser window

You can use the Screen object to get this.

The following is an example of what it would return:

Screen {
    availWidth: 1920,
    availHeight: 1040,
    width: 1920,
    height: 1080,
    colorDepth: 24,
    pixelDepth: 24,
    top: 414,
    left: 1920,
    availTop: 414,
    availLeft: 1920
}

To get your screenWidth variable, just use screen.width, same with screenHeight, you would just use screen.height.

To get your window width and height, it would be screen.availWidth or screen.availHeight respectively.

For the pageX and pageY variables, use window.screenX or Y. Note that this is from the VERY LEFT/TOP OF YOUR LEFT/TOP-est SCREEN. So if you have two screens of width 1920 then a window 500px from the left of the right screen would have an X value of 2420 (1920+500). screen.width/height, however, display the CURRENT screen's width or height.

To get the width and height of your page, use jQuery's $(window).height() or $(window).width().

Again using jQuery, use $("html").offset().top and $("html").offset().left for your pageX and pageY values.

What is the best way to ensure only one instance of a Bash script is running?

One line ultimate solution:

[ "$(pgrep -fn $0)" -ne "$(pgrep -fo $0)" ] && echo "At least 2 copies of $0 are running"

Force drop mysql bypassing foreign key constraint

This might be useful to someone ending up here from a search. Make sure you're trying to drop a table and not a view.

SET foreign_key_checks = 0;
-- Drop tables
drop table ...
-- Drop views
drop view ...
SET foreign_key_checks = 1;

SET foreign_key_checks = 0 is to set foreign key checks to off and then SET foreign_key_checks = 1 is to set foreign key checks back on. While the checks are off the tables can be dropped, the checks are then turned back on to keep the integrity of the table structure.

How to make a new List in Java

List is an interface like Set and has ArrayList and LinkedList as general purpose implementations.

We can create List as:

 List<String> arrayList = new ArrayList<>();
 List<String> linkedList = new LinkedList<>(); 

We can also create a fixed-size list as:

List<String> list = Arrays.asList("A", "B", "C");

We would almost always be using ArrayList opposed to LinkedList implementation:

  1. LinkedList uses a lot of space for objects and performs badly when we have lots of elements.
  2. Any indexed operation in LinkedList requires O(n) time compared to O(1) in ArrayList.
  3. Check this link for more information.

The list created by Arrays.asList above can not be modified structurally but its elements can still be modified.

Java 8

As per doc, the method Collections.unmodifiableList returns an unmodifiable view of the specified list. We can get it like:

Collections.unmodifiableList(Arrays.asList("A", "B", "C"));

Java 9

In case we are using Java 9 then:

List<String> list = List.of("A", "B");

Java 10

In case we are at Java 10 then the method Collectors.unmodifiableList will return an instance of truly unmodifiable list introduced in Java 9. Check this answer for more info about the difference in Collections.unmodifiableList vs Collectors.unmodifiableList in Java 10.

GET URL parameter in PHP

Use this:

$parameter = $_SERVER['QUERY_STRING'];
echo $parameter;

Or just use:

$parameter = $_GET['link'];
echo $parameter ;

How can I convert an RGB image into grayscale in Python?

You can always read the image file as grayscale right from the beginning using imread from OpenCV:

img = cv2.imread('messi5.jpg', 0)

Furthermore, in case you want to read the image as RGB, do some processing and then convert to Gray Scale you could use cvtcolor from OpenCV:

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

How to convert a PIL Image into a numpy array?

def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

You can transform the image into numpy by parsing the image into numpy() function after squishing out the features( unnormalization)

How to disable a particular checkstyle rule for a particular line of code?

Every answer refering to SuppressWarningsFilter is missing an important detail. You can only use the all-lowercase id if it's defined as such in your checkstyle-config.xml. If not you must use the original module name.

For instance, if in my checkstyle-config.xml I have:

<module name="NoWhitespaceBefore"/>

I cannot use:

@SuppressWarnings({"nowhitespacebefore"})

I must, however, use:

@SuppressWarnings({"NoWhitespaceBefore"})

In order for the first syntax to work, the checkstyle-config.xml should have:

<module name="NoWhitespaceBefore">
  <property name="id" value="nowhitespacebefore"/>
</module>

This is what worked for me, at least in the CheckStyle version 6.17.

Expand Python Search Path to Other Source

I read this question looking for an answer, and didn't like any of them.

So I wrote a quick and dirty solution. Just put this somewhere on your sys.path, and it'll add any directory under folder (from the current working directory), or under abspath:

#using.py

import sys, os.path

def all_from(folder='', abspath=None):
    """add all dirs under `folder` to sys.path if any .py files are found.
    Use an abspath if you'd rather do it that way.

    Uses the current working directory as the location of using.py. 
    Keep in mind that os.walk goes *all the way* down the directory tree.
    With that, try not to use this on something too close to '/'

    """
    add = set(sys.path)
    if abspath is None:
        cwd = os.path.abspath(os.path.curdir)
        abspath = os.path.join(cwd, folder)
    for root, dirs, files in os.walk(abspath):
        for f in files:
            if f[-3:] in '.py':
                add.add(root)
                break
    for i in add: sys.path.append(i)

>>> import using, sys, pprint
>>> using.all_from('py') #if in ~, /home/user/py/
>>> pprint.pprint(sys.path)
[
#that was easy
]

And I like it because I can have a folder for some random tools and not have them be a part of packages or anything, and still get access to some (or all) of them in a couple lines of code.

Adding external library in Android studio

Try this:

File > Project Structure > Dependencies Tab > Add module dependency (scope = compile)

Where the module dependency is the project library Android folder.

Page scroll when soft keyboard popped up

check out this.

<activity android:name=".Calculator"
    android:windowSoftInputMode="stateHidden|adjustResize" 
    android:theme="@android:style/Theme.Black.NoTitleBar">
</activity>

Database cluster and load balancing

Database Clustering is actually a mode of synchronous replication between two or possibly more nodes with an added functionality of fault tolerance added to your system, and that too in a shared nothing architecture. By shared nothing it means that the individual nodes actually don't share any physical resources like disk or memory.

As far as keeping the data synchronized is concerned, there is a management server to which all the data nodes are connected along with the SQL node to achieve this(talking specifically about MySQL).

Now about the differences: load balancing is just one result that could be achieved through clustering, the others include high availability, scalability and fault tolerance.

Deep copy vs Shallow Copy

Deep copy literally performs a deep copy. It means, that if your class has some fields that are references, their values will be copied, not references themselves. If, for example you have two instances of a class, A & B with fields of reference type, and perform a deep copy, changing a value of that field in A won't affect a value in B. And vise-versa. Things are different with shallow copy, because only references are copied, therefore, changing this field in a copied object would affect the original object.

What type of a copy does a copy constructor does?

It is implementation - dependent. This means that there are no strict rules about that, you can implement it like a deep copy or shallow copy, however as far as i know it is a common practice to implement a deep copy in a copy constructor. A default copy constructor performs a shallow copy though.

Making text bold using attributed string in swift

For -> Search Television by size

1-way using NString and its Range

let query = "Television"
let headerTitle = "size"
let message = "Search \(query) by \(headerTitle)"
let range = (message as NSString).range(of: query)
let attributedString = NSMutableAttributedString(string: message)
attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: label1.font.pointSize), range: range)
label1.attributedText = attributedString

another without using NString and its Range

let query = "Television"
let headerTitle = "size"
let (searchText, byText) = ("Search ", " by \(headerTitle)")
let attributedString = NSMutableAttributedString(string: searchText)
let byTextAttributedString = NSMutableAttributedString(string: byText)
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: label1.font.pointSize)]
let boldString = NSMutableAttributedString(string: query, attributes:attrs)
attributedString.append(boldString)
attributedString.append(byTextAttributedString)
label1.attributedText = attributedString

swift5

SQL command to display history of queries

You can see the history from ~/.mysql_history. However the content of the file is encoded by wctomb. To view the content:

shell> cat ~/.mysql_history | python2.7 -c "import sys; print(''.join([l.decode('unicode-escape') for l in sys.stdin]))"

Source:Check MySQL query history from command line

Passing an array using an HTML form hidden element

It's better to encode first to a JSON string and then encode with Base64, for example, on the server side in reverse order: use first the base64_decode and then json_decode functions. So you will restore your PHP array.

Regex match text between tags

var root = document.createElement("div");

root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var texts = [].map.call( root.querySelectorAll("b"), function(v){
    return v.textContent || v.innerText || "";
});

//["Bob", "20", "programming"]

CSS styling in Django forms

You can do like this:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    subject.widget.attrs.update({'id' : 'your_id'})

Hope that works.

Ignas

how to make a html iframe 100% width and height?

this code probable help you .

<iframe src="" onload="this.width=screen.width;this.height=screen.height;">

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

I found a more generic solution with the most angular-native solution I can think. Basically you can pass your own comparator to the default filterFilter function. Here's plunker as well.

Javascript change color of text and background to input value

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

HTML:

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

JS:

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

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

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

How do I add to the Windows PATH variable using setx? Having weird problems

If someone want to run it in PowerShell it works like below,

Run Powershell as Administrator

Then

setx /M PATH "$Env:PATH;<path to add>"

To verify, open another Powershell and view PATH as below,

$Env:PATH

What are the ascii values of up down left right?

this is what i get:

Left - 19 Up - 5 Right - 4 Down - 24

Works in Visual Fox Pro

ffprobe or avprobe not found. Please install one

  • Update your version of youtube-dl to the lastest as older version might not support.

     pip install --upgrade youtube_dl
    
  • Install 'ffmpeg' and 'ffprobe' module

     pip install ffmpeg
     pip install ffprobe
    
  • If you face the same issue, then download ffmpeg builds and put all the .exe files to Script folder($path: "Python\Python38-32\Scripts") (Windows OS only)

How to get all count of mongoose model?

Using mongoose.js you can count documents,

  • count all
const count = await Schema.countDocuments();
  • count specific
const count = await Schema.countDocuments({ key: value });

Passing properties by reference in C#

Another trick not yet mentioned is to have the class which implements a property (e.g. Foo of type Bar) also define a delegate delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2); and implement a method ActOnFoo<TX1>(ref Bar it, ActByRef<Bar,TX1> proc, ref TX1 extraParam1) (and possibly versions for two and three "extra parameters" as well) which will pass its internal representation of Foo to the supplied procedure as a ref parameter. This has a couple of big advantages over other methods of working with the property:

  1. The property is updated "in place"; if the property is of a type that's compatible with `Interlocked` methods, or if it is a struct with exposed fields of such types, the `Interlocked` methods may be used to perform atomic updates to the property.
  2. If the property is an exposed-field structure, the fields of the structure may be modified without having to make any redundant copies of it.
  3. If the `ActByRef` method passes one or more `ref` parameters through from its caller to the supplied delegate, it may be possible to use a singleton or static delegate, thus avoiding the need to create closures or delegates at run-time.
  4. The property knows when it is being "worked with". While it is always necessary to use caution executing external code while holding a lock, if one can trust callers not to do too do anything in their callback that might require another lock, it may be practical to have the method guard the property access with a lock, such that updates which aren't compatible with `CompareExchange` could still be performed quasi-atomically.

Passing things be ref is an excellent pattern; too bad it's not used more.

How do I disable a href link in JavaScript?

Use all three of the following: Event.preventDefault();, Event.stopPropagation();, and return false;. Each explained...

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Webdocs.)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (i.e., if two links overlapped visually in the UI).

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. (Source: MDN Webdocs.)

  • return false; : To indicate to the onevent handler that we are cancelling the link-clicking behavior.

The return value from the handler determines if the event is canceled. (Source: MDN Webdocs.)

Full Working JSBin Demo.

StackOverflow Demo...

_x000D_
_x000D_
document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' + e.target.id);
  e.preventDefault();
  e.stopPropagation();
  return false;
});
_x000D_
<a href="https://www.wikipedia.com/" id="my-link" target="_blank">Link</a>
_x000D_
_x000D_
_x000D_

Dynamic Web Module 3.0 -- 3.1

If you want to use version 3.1 you need to use the following schema:

  • http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd

Note that 3.0 and 3.1 are different: in 3.1 there's no Sun mentioned, so simply changing 3_0.xsd to 3_1.xsd won't work.

This is how it should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">

</web-app>

Also, make sure you're depending on the latest versions in your pom.xml. That is,

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        ...
    </configuration>
</plugin>

and

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Finally, you should compile with Java 7 or 8:

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

Convert a Unicode string to an escaped ASCII string

As a one-liner:

var result = Regex.Replace(input, @"[^\x00-\x7F]", c => 
    string.Format(@"\u{0:x4}", (int)c.Value[0]));

How to keep footer at bottom of screen

Perhaps the easiest is to use position: absolute to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.

css:

<style>
  body {
    margin: 0 0 20px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    height: 20px;
    background: #f0f0f0;
    width: 100%;
  }
</style>

Here is the html main content.

<div class="footer"> Here is the footer. </div>

Convert number to varchar in SQL with formatting

Here's an alternative following the last answer

declare @t tinyint,@v tinyint
set @t=23
set @v=232
Select replace(str(@t,4),' ','0'),replace(str(@t,5),' ','0')

This will work on any number and by varying the length of the str() function you can stipulate how many leading zeros you require. Provided of course that your string length is always >= maximum number of digits your number type can hold.

Recommended way to insert elements into map

  1. insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
  2. operator[] needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

How to get the number of characters in a string

You can try RuneCountInString from the utf8 package.

returns the number of runes in p

that, as illustrated in this script: the length of "World" might be 6 (when written in Chinese: "??"), but its rune count is 2:

package main
    
import "fmt"
import "unicode/utf8"
    
func main() {
    fmt.Println("Hello, ??", len("??"), utf8.RuneCountInString("??"))
}

Phrozen adds in the comments:

Actually you can do len() over runes by just type casting.
len([]rune("??")) will print 2. At leats in Go 1.3.


And with CL 108985 (May 2018, for Go 1.11), len([]rune(string)) is now optimized. (Fixes issue 24923)

The compiler detects len([]rune(string)) pattern automatically, and replaces it with for r := range s call.

Adds a new runtime function to count runes in a string. Modifies the compiler to detect the pattern len([]rune(string)) and replaces it with the new rune counting runtime function.

RuneCount/lenruneslice/ASCII        27.8ns ± 2%  14.5ns ± 3%  -47.70%
RuneCount/lenruneslice/Japanese     126ns ± 2%   60  ns ± 2%  -52.03%
RuneCount/lenruneslice/MixedLength  104ns ± 2%   50  ns ± 1%  -51.71%

Stefan Steiger points to the blog post "Text normalization in Go"

What is a character?

As was mentioned in the strings blog post, characters can span multiple runes.
For example, an 'e' and '?´?´' (acute "\u0301") can combine to form 'é' ("e\u0301" in NFD). Together these two runes are one character.

The definition of a character may vary depending on the application.
For normalization we will define it as:

  • a sequence of runes that starts with a starter,
  • a rune that does not modify or combine backwards with any other rune,
  • followed by possibly empty sequence of non-starters, that is, runes that do (typically accents).

The normalization algorithm processes one character at at time.

Using that package and its Iter type, the actual number of "character" would be:

package main
    
import "fmt"
import "golang.org/x/text/unicode/norm"
    
func main() {
    var ia norm.Iter
    ia.InitString(norm.NFKD, "école")
    nc := 0
    for !ia.Done() {
        nc = nc + 1
        ia.Next()
    }
    fmt.Printf("Number of chars: %d\n", nc)
}

Here, this uses the Unicode Normalization form NFKD "Compatibility Decomposition"


Oliver's answer points to UNICODE TEXT SEGMENTATION as the only way to reliably determining default boundaries between certain significant text elements: user-perceived characters, words, and sentences.

For that, you need an external library like rivo/uniseg, which does Unicode Text Segmentation.

That will actually count "grapheme cluster", where multiple code points may be combined into one user-perceived character.

package uniseg
    
import (
    "fmt"
    
    "github.com/rivo/uniseg"
)
    
func main() {
    gr := uniseg.NewGraphemes("!")
    for gr.Next() {
        fmt.Printf("%x ", gr.Runes())
    }
    // Output: [1f44d 1f3fc] [21]
}

Two graphemes, even though there are three runes (Unicode code points).

You can see other examples in "How to manipulate strings in GO to reverse them?"

? alone is one grapheme, but, from unicode to code points converter, 4 runes:

How can I execute Shell script in Jenkinsfile?

Previous answers are correct but here is one more way of doing this and some tips:

Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there

Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh

enter image description here enter image description here

things to watch for /tips:

  • Environment variables, if your job is running at the same time then you need to worry about concurrency issues. One job may be setting the value of environment variables and the next may use the value or take some action based on that incorrectly.
  • Make sure all paths are fully qualified
  • Think about logging /var/log or somewhere so you would also have something to go to on the server (optional)
  • thing about space issue and permissions, running out of space and permission issues are very common in linux environment
  • Alerting and make sure your script/job fails the jenkin jobs when your script fails

How do I get the Git commit count?

git shortlog is one way.

Playing a MP3 file in a WinForm application

You can use the mciSendString API to play an MP3 or a WAV file:

[DllImport("winmm.dll")]
public static extern uint mciSendString( 
    string lpstrCommand,
    StringBuilder lpstrReturnString,
    int uReturnLength,
    IntPtr hWndCallback
);

mciSendString(@"close temp_alias", null, 0, IntPtr.Zero);
mciSendString(@"open ""music.mp3"" alias temp_alias", null, 0, IntPtr.Zero);
mciSendString("play temp_alias repeat", null, 0, IntPtr.Zero);

Spring Boot - How to log all requests and responses with exceptions in single place?

After adding Actuators to the spring boot bassed application you have /trace endpoint available with latest requests informations. This endpoint is working based on TraceRepository and default implementation is InMemoryTraceRepository that saves last 100 calls. You can change this by implementing this interface by yourself and make it available as a Spring bean. For example to log all requests to log (and still use default implementation as a basic storage for serving info on /trace endpoint) I'm using this kind of implementation:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.trace.InMemoryTraceRepository;
import org.springframework.boot.actuate.trace.Trace;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


@Component
public class LoggingTraceRepository implements TraceRepository {

  private static final Logger LOG = LoggerFactory.getLogger(LoggingTraceRepository.class);
  private final TraceRepository delegate = new InMemoryTraceRepository();

  @Override
  public List<Trace> findAll() {
    return delegate.findAll();
  }

  @Override
  public void add(Map<String, Object> traceInfo) {
    LOG.info(traceInfo.toString());
    this.delegate.add(traceInfo);
  }
}

This traceInfo map contains basic informations about request and response in this kind of form: {method=GET, path=/api/hello/John, headers={request={host=localhost:8080, user-agent=curl/7.51.0, accept=*/*}, response={X-Application-Context=application, Content-Type=text/plain;charset=UTF-8, Content-Length=10, Date=Wed, 29 Mar 2017 20:41:21 GMT, status=200}}}. There is NO response content here.

EDIT! Logging POST data

You can access POST data by overriding WebRequestTraceFilter, but don't think it is a good idea (e.g. all uploaded file content will go to logs) Here is sample code, but don't use it:

package info.fingo.nuntius.acuate.trace;

import org.apache.commons.io.IOUtils;
import org.springframework.boot.actuate.trace.TraceProperties;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.boot.actuate.trace.WebRequestTraceFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class CustomWebTraceFilter extends WebRequestTraceFilter {

  public CustomWebTraceFilter(TraceRepository repository, TraceProperties properties) {
    super(repository, properties);
}

  @Override
  protected Map<String, Object> getTrace(HttpServletRequest request) {
    Map<String, Object> trace = super.getTrace(request);
    String multipartHeader = request.getHeader("content-type");
    if (multipartHeader != null && multipartHeader.startsWith("multipart/form-data")) {
        Map<String, Object> parts = new LinkedHashMap<>();
        try {
            request.getParts().forEach(
                    part -> {
                        try {
                            parts.put(part.getName(), IOUtils.toString(part.getInputStream(), Charset.forName("UTF-8")));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
        if (!parts.isEmpty()) {
            trace.put("multipart-content-map", parts);
        }
    }
    return trace;
  }
}

Open Form2 from Form1, close Form1 from Form2

I did this once for my project, to close one application and open another application.

    System.Threading.Thread newThread;
    Form1 frmNewForm = new Form1;

   newThread = new System.Threading.Thread(new System.Threading.ThreadStart(frmNewFormThread));
this.Close();
        newThread.SetApartmentState(System.Threading.ApartmentState.STA);
        newThread.Start();

And add the following Method. Your newThread.Start will call this method.

    public void frmNewFormThread)()
    {

        Application.Run(frmNewForm);

    }

Build unsigned APK file with Android Studio

--- Create new config in signingConfigs

unsigned {
        //do not sign
    }

--- Create build type in buildTypes

unsigned {
        versionNameSuffix '-unsigned'
    }

--- Go to build variants and chose unsigned standard. Build project.

--- Go to "outputs/apk" and find "XXX-unsigned.apk". To check if it is unsigned try to install it to device - you'll fail.

ADB Driver and Windows 8.1

In Windows 7, 8 or 8.1, in Devices Manager:

  1. Select tree 'Android Device': remove 'Android Composite ADB Interface' [?]
  2. Press on main root of devices tree and call context menu (by right mouse click) and click on 'Update configuration'
  3. After updating your device should appear in 'Other devices'
  4. Select your device, call context menu from it and choose 'Update driver' and perform this updating

insert multiple rows into DB2 database

I'm assuming you're using DB2 for z/OS, which unfortunately (for whatever reason, I never really understood why) doesn't support using a values-list where a full-select would be appropriate.

You can use a select like below. It's a little unwieldy, but it works:

INSERT INTO tableName (col1, col2, col3, col4, col5) 
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1

Your statement would work on DB2 for Linux/Unix/Windows (LUW), at least when I tested it on my LUW 9.7.

Example to use shared_ptr?

Through Boost you can do it >

std::vector<boost::any> vecobj;
    boost::shared_ptr<string> sharedString1(new string("abcdxyz!"));    
    boost::shared_ptr<int> sharedint1(new int(10));
    vecobj.push_back(sharedString1);
    vecobj.push_back(sharedint1);

> for inserting different object type in your vector container. while for accessing you have to use any_cast, which works like dynamic_cast, hopes it will work for your need.

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

HTML5 textarea placeholder not appearing

I had the same issue, only using a .pug file (similar to .jade). I realized that it was also a space issue, following the end of my closing parentheses. In my example, you need to highlight the text after (placeholder="YOUR MESSAGE") to see:

BEFORE:

form.form-horizontal(method='POST')
  .form-group
    textarea.form-control(placeholder="YOUR MESSAGE") 
  .form-group  
    button.btn.btn-primary(type='submit') SUBMIT

AFTER:

form.form-horizontal(method='POST')
  .form-group
    textarea.form-control(placeholder="YOUR MESSAGE")
  .form-group  
    button.btn.btn-primary(type='submit') SUBMIT

How to install trusted CA certificate on Android device?

Here's an alternate solution that actually adds your certificate to the built in list of default certificates: Trusting all certificates using HttpClient over HTTPS

However, it will only work for your application. There's no way to programmatically do it for all applications on a user's device, since that would be a security risk.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.