Programs & Examples On #Google eclipse plugin

Google Plugin for Eclipse (GPE) is a set of software development tools that enables Java developers to quickly design, build, optimize, and deploy cloud-based applications.

How to create duplicate table with new name in SQL Server 2008

My SQL Server Management Studio keeps asking me how I can make it better, I have an idea! The ability to highlight a table and then, ctrl C, ctrl V! would be great and the answer to this question at the same time!

Visual Studio: How to break on handled exceptions?

From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException) to make it break on handled exceptions.

Step 1 Step 1 Step 2 Step 2

Detecting when a div's height changes using jQuery

You can use the DOMSubtreeModified event

$(something).bind('DOMSubtreeModified' ...

But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.

Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.

Downside: IE and Opera don't implement this event.

How to implement private method in ES6 class with Traceur

There are no private, public or protected keywords in current ECMAScript 6 specification.

So Traceur does not support private and public. 6to5 (currently it's called "Babel") realizes this proposal for experimental purpose (see also this discussion). But it's just proposal, after all.

So for now you can just simulate private properties through WeakMap (see here). Another alternative is Symbol - but it doesn't provide actual privacy as the property can be easily accessed through Object.getOwnPropertySymbols.

IMHO the best solution at this time - just use pseudo privacy. If you frequently use apply or call with your method, then this method is very object specific. So it's worth to declare it in your class just with underscore prefix:

class Animal {

    _sayHi() {
        // do stuff
    }
}

Remove Item in Dictionary based on Value

Are you trying to remove a single value or all matching values?

If you are trying to remove a single value, how do you define the value you wish to remove?

The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.

If you wish to remove all matching instances of the same value, you can do this:

foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
    dic.Remove(item.Key);
}

And if you wish to remove the first matching instance, you can query to find the first item and just remove that:

var item = dic.First(kvp => kvp.Value == value);

dic.Remove(item.Key);

Note: The ToList() call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.

How to increase editor font size?

Very Simple .

Go to File then Settings then Select Editor then Font and change the size .

File -> Settings -> Editor -> Colors & Fonts -> Font.

Android sqlite how to check if a record exists

Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:

  public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
    String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
    return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
  }

Arraylist swap elements

for (int i = 0; i < list.size(); i++) {
        if (i < list.size() - 1) {
            if (list.get(i) > list.get(i + 1)) {
                int j = list.get(i);
                list.remove(i);
                list.add(i, list.get(i));
                list.remove(i + 1);
                list.add(j);
                i = -1;
            }
        }
    }

setAttribute('display','none') not working

It works for me

setAttribute('style', 'display:none');

How to use java.Set

Since it is a HashSet you will need to override hashCode and equals methods. http://preciselyconcise.com/java/collections/d_set.php has an example explaining how to implement hashCode and equals methods

Move an array element from one array position to another

Got this idea from @Reid of pushing something in the place of the item that is supposed to be moved to keep the array size constant. That does simplify calculations. Also, pushing an empty object has the added benefits of being able to search for it uniquely later on. This works because two objects are not equal until they are referring to the same object.

({}) == ({}); // false

So here's the function which takes in the source array, and the source, destination indexes. You could add it to the Array.prototype if needed.

function moveObjectAtIndex(array, sourceIndex, destIndex) {
    var placeholder = {};
    // remove the object from its initial position and
    // plant the placeholder object in its place to
    // keep the array length constant
    var objectToMove = array.splice(sourceIndex, 1, placeholder)[0];
    // place the object in the desired position
    array.splice(destIndex, 0, objectToMove);
    // take out the temporary object
    array.splice(array.indexOf(placeholder), 1);
}

UITableView Cell selected Color?

Swift 3: for me it worked when you put it in the cellForRowAtIndexPath: method

let view = UIView()
view.backgroundColor = UIColor.red
cell.selectedBackgroundView = view

How to decrypt an encrypted Apple iTunes iPhone backup?

You should grab a copy of Erica Sadun's mdhelper command line utility (OS X binary & source). It supports listing and extracting the contents of iPhone/iPod Touch backups, including address book & SMS databases, and other application metadata and settings.

What are the ways to sum matrix elements in MATLAB?

You are trying to sum up all the elements of 2-D Array

In Matlab use

Array_Sum = sum(sum(Array_Name));

How to set the custom border color of UIView programmatically?

We can create method for it. Simply use it.

public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
    self.layer.borderWidth = width
    self.layer.cornerRadius = radius
    self.layer.shouldRasterize = false
    self.layer.rasterizationScale = 2
    self.clipsToBounds = true
    self.layer.masksToBounds = true
    let cgColor: CGColor = color.cgColor
    self.layer.borderColor = cgColor
}

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

Git Ignores and Maven targets

add following lines in gitignore, from all undesirable files

/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

Make xargs execute the command once for each line of input

execute ant task clean-all on every build.xml on current or sub-folder.

find . -name 'build.xml' -exec ant -f {} clean-all \;

Error: "an object reference is required for the non-static field, method or property..."

The error message means that you need to invoke volteado and siprimo on an instance of the Program class. E.g.:

...
Program p = new Program();
long av = p.volteado(a); // av is "a" but swapped

if (p.siprimo(a) == false && p.siprimo(av) == false)
...

They cannot be invoked directly from the Main method because Main is static while volteado and siprimo are not.

The easiest way to fix this is to make the volteado and siprimo methods static:

private static bool siprimo(long a)
{
    ...
}

private static bool volteado(long a)
{
   ...
}

Why doesn't [01-12] range work as expected?

A character class in regular expressions, denoted by the [...] syntax, specifies the rules to match a single character in the input. As such, everything you write between the brackets specify how to match a single character.

Your pattern, [01-12] is thus broken down as follows:

  • 0 - match the single digit 0
  • or, 1-1, match a single digit in the range of 1 through 1
  • or, 2, match a single digit 2

So basically all you're matching is 0, 1 or 2.

In order to do the matching you want, matching two digits, ranging from 01-12 as numbers, you need to think about how they will look as text.

You have:

  • 01-09 (ie. first digit is 0, second digit is 1-9)
  • 10-12 (ie. first digit is 1, second digit is 0-2)

You will then have to write a regular expression for that, which can look like this:

  +-- a 0 followed by 1-9
  |
  |      +-- a 1 followed by 0-2
  |      |
<-+--> <-+-->
0[1-9]|1[0-2]
      ^
      |
      +-- vertical bar, this roughly means "OR" in this context

Note that trying to combine them in order to get a shorter expression will fail, by giving false positive matches for invalid input.

For instance, the pattern [0-1][0-9] would basically match the numbers 00-19, which is a bit more than what you want.

I tried finding a definite source for more information about character classes, but for now all I can give you is this Google Query for Regex Character Classes. Hopefully you'll be able to find some more information there to help you.

Why doesn't list have safe "get" method like dictionary?

For small index values you can implement

my_list.get(index, default)

as

(my_list + [default] * (index + 1))[index]

If you know in advance what index is then this can be simplified, for example if you knew it was 1 then you could do

(my_list + [default, default])[index]

Because lists are forward packed the only fail case we need to worry about is running off the end of the list. This approach pads the end of the list with enough defaults to guarantee that index is covered.

How to get the text of the selected value of a dropdown list?

You can use option:selected to get the chosen option of the select element, then the text() method:

$("select option:selected").text();

Here's an example:

_x000D_
_x000D_
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option value="1">Volvo</option>_x000D_
    <option value="2" selected="selected">Saab</option>_x000D_
    <option value="3">Mercedes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Pretty printing XML with javascript

All of the javascript functions given here won't work for an xml document having unspecified white spaces between the end tag '>' and the start tag '<'. To fix them, you just need to replace the first line in the functions

var reg = /(>)(<)(\/*)/g;

by

var reg = /(>)\s*(<)(\/*)/g;

base64 encoded images in email signatures

Important

My answer below shows how to embed images using data URIs. This is useful for the web, but will not work reliably for most email clients. For email purposes be sure to read Shadow2531's answer.


Base-64 data is legal in an img tag and I believe your question is how to properly insert such an image tag.

You can use an online tool or a few lines of code to generate the base 64 string.

The syntax to source the image from inline data is:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

http://en.wikipedia.org/wiki/Data_URI_scheme

Apache Tomcat :java.net.ConnectException: Connection refused

Was the Tomcat running before you restarted it? Was there any other app listening on this port?

The exception is thrown because there was nobody listening on the command port (see <Server port="..." in $tomcat_home/conf/server.xml).

Reset select2 value and show placeholder

So, to reset the form some of you will have a reset button. Add the following code inside the script tag

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
    $("#select_field_id").select2({
    placeholder: "this is a placeholder",
    });
});

Or just to empty select field without keeping a placeholder:

$('.your_btn_class').click(function(){
    $('#select_field_id').val([]);
 });

How to launch html using Chrome at "--allow-file-access-from-files" mode?

Search for the path of your Chrome executable and then, on your cmd, try :

> "C:\PathTo\Chrome.exe" --allow-file-access-from-files

Source

EDIT : As I see on your question, don't forget that Windows is a little bit similar to Unix, so when you type "chrome ...", cmd will search for Chrome in the PATH, but in general the Chrome folder isn't on the PATH. Also, you don't specify an extension for your executable... So if you move to Chrome's folder, this command will probably work too :

> .\chrome.exe --allow-file-access-from-files

Extract month and year from a zoo::yearmon object

The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:

cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012

Splitting String with delimiter

split doesn't work that way in groovy. you have to use tokenize...

See the docs:

http://groovy-lang.org/gdk.html#split()

Session only cookies with Javascript

Yes, that is correct.

Not putting an expires part in will create a session cookie, whether it is created in JavaScript or on the server.

See https://stackoverflow.com/a/532660/1901857

This could be due to the service endpoint binding not using the HTTP protocol

I had this problem because I configured my WCF Service to return a System.Data.DataTable.

It worked fine in my test HTML page, but blew up when I put this in my Windows Form application.

I had to go in and change the Service's Operational Contract signature from DataTable to DataSet and return the data accordingly.

If you have this problem, you may want to add an additional Operational Contract to your Service so you do not have to worry about breaking code that rely on existing Services.

Retrieve data from a ReadableStream object?

I dislike the chaining thens. The second then does not have access to status. As stated before 'response.json()' returns a promise. Returning the then result of 'response.json()' in a acts similar to a second then. It has the added bonus of being in scope of the response.

return fetch(url, params).then(response => {
    return response.json().then(body => {
        if (response.status === 200) {
            return body
        } else {
            throw body
        }
    })
})

splitting a string into an array in C++ without using vector

#define MAXSPACE 25

string line =  "test one two three.";
string arr[MAXSPACE];
string search = " ";
int spacePos;
int currPos = 0;
int k = 0;
int prevPos = 0;

do
{

    spacePos = line.find(search,currPos);

    if(spacePos >= 0)
    {

        currPos = spacePos;
        arr[k] = line.substr(prevPos, currPos - prevPos);
        currPos++;
        prevPos = currPos;
        k++;
    }


}while( spacePos >= 0);

arr[k] = line.substr(prevPos,line.length());

for(int i = 0; i < k; i++)
{
   cout << arr[i] << endl;
}

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just

=VLOOKUP(A1, B:C, 2, FALSE) 

works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

make sounds (beep) with c++

If you're using Windows OS then there is a function called Beep()

#include <iostream> 
#include <windows.h> // WinApi header 

using namespace std;

int main() 
{ 
    Beep(523,500); // 523 hertz (C5) for 500 milliseconds     
    cin.get(); // wait 
    return 0; 
}

Source: http://www.daniweb.com/forums/thread15252.html

For Linux based OS there is:

echo -e "\007" >/dev/tty10

And if you do not wish to use Beep() in windows you can do:

echo "^G"

Source: http://www.frank-buss.de/beep/index.html

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I used the following on Mac OSX.

currDate=`date +%Y%m%d`
epochDate=$(date -j -f "%Y%m%d" "${currDate}" "+%s")

CSS transition with visibility not working

This is not a bug- you can only transition on ordinal/calculable properties (an easy way of thinking of this is any property with a numeric start and end number value..though there are a few exceptions).

This is because transitions work by calculating keyframes between two values, and producing an animation by extrapolating intermediate amounts.

visibility in this case is a binary setting (visible/hidden), so once the transition duration elapses, the property simply switches state, you see this as a delay- but it can actually be seen as the final keyframe of the transition animation, with the intermediary keyframes not having been calculated (what constitutes the values between hidden/visible? Opacity? Dimension? As it is not explicit, they are not calculated).

opacity is a value setting (0-1), so keyframes can be calculated across the duration provided.

A list of transitionable (animatable) properties can be found here

Keep values selected after form submission

<form method="get" action="">
 <select name="name" value="<?php echo $_GET['name'];?>">
   <option value="a">a</option>
   <option value="b">b</option>
 </select>
 <select name="location" value="<?php echo $_GET['location'];?>">
   <option value="x">x</option>
   <option value="y">y</option>
 </select>
   <input type="submit" value="Submit" class="submit" />
</form>

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

We actually override static methods (in delphi), it's a bit ugly, but it works just fine for our needs.

We use it so the classes can have a list of their available objects without the class instance, for example, we have a method that looks like this:

class function AvailableObjects: string; override;
begin
  Result := 'Object1, Object2';
end; 

It's ugly but necessary, this way we can instantiate just what is needed, instead of having all the classes instantianted just to search for the available objects.

This was a simple example, but the application itself is a client-server application which has all the classes available in just one server, and multiple different clients which might not need everything the server has and will never need an object instance.

So this is much easier to maintain than having one different server application for each client.

Hope the example was clear.

Download File Using jQuery

 var link=document.createElement('a');
 document.body.appendChild(link);
 link.href=url;
 link.click();

How do I pass a string into subprocess.Popen (using the stdin argument)?

I'm a bit surprised nobody suggested creating a pipe, which is in my opinion the far simplest way to pass a string to stdin of a subprocess:

read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)

subprocess.check_call(['your-command'], stdin=read)

sorting and paging with gridview asp.net

Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.

The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.

There are other methods, too, such as persisting user profiles.

I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx

To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). In your case, you're calling window.open later, not during the event, because $.getJSON is asynchronous.

You have two options:

  1. Do something else, rather than window.open.

  2. Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON is equivalent to:

    $.ajax({
      url: url,
      dataType: 'json',
      data: data,
      success: callback
    });
    

    ...and so you can make your $.getJSON call synchronous by mapping your params to the above and adding async: false:

    $.ajax({
        url:      "redirect/" + pageId,
        async:    false,
        dataType: "json",
        data:     {},
        success:  function(status) {
            if (status == null) {
                alert("Error in verifying the status.");
            } else if(!status) {
                $("#agreement").dialog("open");
            } else {
                window.open(redirectionURL);
            }
        }
    });
    

    Again, I don't advocate synchronous ajax calls if you can find any other way to achieve your goal. But if you can't, there you go.

    Here's an example of code that fails the test because of the asynchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version doesn't work, because the window.open is
      // not during the event processing
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.getJSON("http://jsbin.com/uriyip", function() {
          window.open("http://jsbin.com/ubiqev");
        });
      });
    });
    

    And here's an example that does work, using a synchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version does work, because the window.open is
      // during the event processing. But it uses a synchronous
      // ajax call, locking up the browser UI while the call is
      // in progress.
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.ajax({
          url:      "http://jsbin.com/uriyip",
          async:    false,
          dataType: "json",
          success:  function() {
            window.open("http://jsbin.com/ubiqev");
          }
        });
      });
    });
    

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

How to create an empty array in Swift?

If you want to declare an empty array of string type you can do that in 5 different way:-

var myArray: Array<String> = Array()
var myArray = [String]()
var myArray: [String] = []
var myArray = Array<String>()
var myArray:Array<String> = []

Array of any type :-

    var myArray: Array<AnyObject> = Array()
    var myArray = [AnyObject]()
    var myArray: [AnyObject] = []
    var myArray = Array<AnyObject>()
    var myArray:Array<AnyObject> = []

Array of Integer type :-

    var myArray: Array<Int> = Array()
    var myArray = [Int]()
    var myArray: [Int] = []
    var myArray = Array<Int>()
    var myArray:Array<Int> = []

Any tools to generate an XSD schema from an XML instance document?

Altova XmlSpy does this well - you can find an overview here

How to resolve git stash conflict without commit?

Don't follow other answers

Well, you can follow them :). But I don't think that doing a commit and then resetting the branch to remove that commit and similar workarounds suggested in other answers are the clean way to solve this issue.

Clean solution

The following solution seems to be much cleaner to me and it's also suggested by the Git itself — try to execute git status in the repository with a conflict:

Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add <file>..." to mark resolution)

So let's do what Git suggests (without doing any useless commits):

  1. Manually (or using some merge tool, see below) resolve the conflict(s).
  2. Use git reset to mark conflict(s) as resolved and unstage the changes. You can execute it without any parameters and Git will remove everything from the index. You don't have to execute git add before.
  3. Finally, remove the stash with git stash drop, because Git doesn't do that on conflict.

Translated to the command-line:

$ git stash pop

# ...resolve conflict(s)

$ git reset

$ git stash drop

Explanation of the default behavior

There are two ways of marking conflicts as resolved: git add and git reset. While git reset marks the conflicts as resolved and removes files from the index, git add also marks the conflicts as resolved, but keeps files in the index.

Adding files to the index after a conflict is resolved is on purpose. This way you can differentiate the changes from the previous stash and changes you made after the conflict was resolved. If you don't like it, you can always use git reset to remove everything from the index.

Merge tools

I highly recommend using any of 3-way merge tools for resolving conflicts, e.g. KDiff3, Meld, etc., instead of doing it manually. It usually solves all or majority of conflicts automatically itself. It's huge time-saver!

How to include layout inside layout?

Use <include /> tag.

          <include 
            android:id="@+id/some_id_if_needed"
            layout="@layout/some_layout"/>

Also, read Creating Reusable UI Components and Merging Layouts articles.

SQLite - getting number of rows in a database

You can query the actual number of rows with

SELECT Count(*) FROM tblName
see https://www.w3schools.com/sql/sql_count_avg_sum.asp

How to define a two-dimensional array?

In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:

matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)

Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a "two-dimensional list":

from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Have a reference of stream form successHandle

var streamRef;

var handleVideo = function (stream) {
    streamRef = stream;
}

//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
    val.stop();
});

Easy way to test an LDAP User's Credentials

Note, if you don't know your full bind DN, you can also just use your normal username or email with -U

ldapsearch -v -h contoso.com -U [email protected] -w 'MY_PASSWORD' -b 'DC=contoso,DC=com' '(objectClass=computer)'

twitter bootstrap typeahead ajax example

I did some modifications on the jquery-ui.min.js:

//Line 319 ORIG:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
// NEW:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...

// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....

// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
// NEW:
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`

and add following css

.dropdown-menu {
    max-width: 920px;
}
.ui-menu-item {
    cursor: pointer;        
}

Works perfect.

Entity Framework Refresh context?

EF 6

In my scenario, Entity Framework was not picking up the newly updated data. The reason might be the data was updated outside of its scope. Refreshing data after fetching resolved my issue.

private void RefreshData(DBEntity entity)
{
    if (entity == null) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entity);
}

private void RefreshData(List<DBEntity> entities)
{
    if (entities == null || entities.Count == 0) return;

    ((IObjectContextAdapter)DbContext).ObjectContext.RefreshAsync(RefreshMode.StoreWins, entities);
}

How do you update a DateTime field in T-SQL?

The string literal is pased according to the current dateformat setting, see SET DATEFORMAT. One format which will always work is the '20090525' one.

Now, of course, you need to define 'does not work'. No records gets updated? Perhaps the Id=1 doesn't match any record...

If it says 'One record changed' then perhaps you need to show us how you verify...

Check if string contains a value in array

$string = 'my domain name is website3.com';
$a = array('website1.com','website2.com','website3.com');

$result = count(array_filter($a, create_function('$e','return strstr("'.$string.'", $e);')))>0; 
var_dump($result );

output

bool(true)

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

How do I convert an Array to a List<object> in C#?

You can try this,

using System.Linq;
string[] arrString = { "A", "B", "C"};
List<string> listofString = arrString.OfType<string>().ToList();

Hope, this code helps you.

ActiveXObject creation error " Automation server can't create object"

This is caused by Security settings for internet explorer. You can fix this,by changing internet explorer settings.Go To Settings->Internet Options->Security Tabs. You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites. Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button. It opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.

enter image description here

enter image description here

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Try starting IntelliJ from terminal. You can find application file under: /Applications/IntelliJ\ IDEA\ 14.app/Contents/MacOS

Create a Date with a set timezone without using a string representation

// My clock 2018-07-25, 00:26:00 (GMT+7)
let date = new Date(); // 2018-07-24:17:26:00 (Look like GMT+0)
const myTimeZone = 7; // my timeZone 
// my timeZone = 7h = 7 * 60 * 60 * 1000 (millisecond);
// 2018-07-24:17:26:00 = x (milliseconds)
// finally, time in milliseconds (GMT+7) = x + myTimezone 
date.setTime( date.getTime() + myTimeZone * 60 * 60 * 1000 );
// date.toISOString() = 2018-07-25, 00:26:00 (GMT+7)

Guzzle 6: no more json() method for responses

I use $response->getBody()->getContents() to get JSON from response. Guzzle version 6.3.0.

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

How to change the hosts file on android

Probably the easiest way would be use this app Hosts Editor . You need to have root

How to access command line arguments of the caller inside a function?

You can use the shift keyword (operator?) to iterate through them. Example:

#!/bin/bash
function print()
{
    while [ $# -gt 0 ]
    do
        echo $1;
        shift 1;
    done
}
print $*;

How Can I Truncate A String In jQuery?

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }

Apache HttpClient Interim Error: NoHttpResponseException

I have faced same issue, I resolved by adding "connection: close" as extention,

Step 1: create a new class ConnectionCloseExtension

import com.github.tomakehurst.wiremock.common.FileSource;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.extension.ResponseTransformer;
import com.github.tomakehurst.wiremock.http.HttpHeader;
import com.github.tomakehurst.wiremock.http.HttpHeaders;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.Response;

public class ConnectionCloseExtension extends ResponseTransformer {
  @Override
  public Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    return Response.Builder
        .like(response)
        .headers(HttpHeaders.copyOf(response.getHeaders())
            .plus(new HttpHeader("Connection", "Close")))
        .build();
  }

  @Override
  public String getName() {
    return "ConnectionCloseExtension";
  }
}

Step 2: set extension class in wireMockServer like below,

final WireMockServer wireMockServer = new WireMockServer(options()
                .extensions(ConnectionCloseExtension.class)
                .port(httpPort));

How to add a changed file to an older (not last) commit in Git

with git 1.7, there's a really easy way using git rebase:

stage your files:

git add $files

create a new commit and re-use commit message of your "broken" commit

git commit -c master~4

prepend fixup! in the subject line (or squash! if you want to edit commit (message)):

fixup! Factored out some common XPath Operations

use git rebase -i --autosquash to fixup your commit

What is the "__v" field in Mongoose

Well, I can't see Tony's solution...so I have to handle it myself...


If you don't need version_key, you can just:

var UserSchema = new mongoose.Schema({
    nickname: String,
    reg_time: {type: Date, default: Date.now}
}, {
    versionKey: false // You should be aware of the outcome after set to false
});

Setting the versionKey to false means the document is no longer versioned.

This is problematic if the document contains an array of subdocuments. One of the subdocuments could be deleted, reducing the size of the array. Later on, another operation could access the subdocument in the array at it's original position.

Since the array is now smaller, it may accidentally access the wrong subdocument in the array.

The versionKey solves this by associating the document with the a versionKey, used by mongoose internally to make sure it accesses the right collection version.

More information can be found at: http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html

What method in the String class returns only the first N characters?

public static string TruncateLongString(this string str, int maxLength)
{
    if (string.IsNullOrEmpty(str)) return str;

    return str.Substring(0, Math.Min(str.Length, maxLength));
}

How to call C++ function from C?

You can prefix the function declaration with extern “C” keyword, e.g.

extern “C” int Mycppfunction()

{

// Code goes here

return 0;

}

For more examples you can search more on Google about “extern” keyword. You need to do few more things, but it's not difficult you'll get lots of examples from Google.

jquery ui Dialog: cannot call methods on dialog prior to initialization

Try this instead

$(document).ready(function() {
  $("#divDialog").dialog(opt).dialog("open");
});

You can also do:

var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");

That's because the dialog is not stored in $('#divDialog'), but on a new div that is created on the fly and returned by the .dialog(opt) function.

Java error: Only a type can be imported. XYZ resolves to a package

My bet is that you have a package called org.ivec.eresearch.knowledgeportal.model.category (small c) and are running on a non-case sensitive filesystem like Windows or Mac. It seems that the compiler gets confused when a class and package exist.

You can either renamed the class "Category" or the package "category" and this error will go away. Unfortunately I'm not sure if this is a Tomcat or ECJ bug.

Accessing an SQLite Database in Swift

The best you can do is import the dynamic library inside a bridging header:

  1. Add libsqlite3.dylib to your "Link Binary With Libraries" build phase
  2. Create a "Bridging-Header.h" and add #import <sqlite3.h> to the top
  3. set "Bridging-Header.h" for the "Objective-C Bridging Header" setting in Build Settings under "Swift Compiler - Code Generation"

You will then be able to access all of the c methods like sqlite3_open from your swift code.

However, you may just want to use FMDB and import that through the bridging header as that is a more object oriented wrapper of sqlite. Dealing with C pointers and structs will be cumbersome in Swift.

SQL: sum 3 columns when one column has a null value?

I would try this:

select sum (case when TotalHousM is null then 0 else TotalHousM end)
       + (case when TotalHousT is null then 0 else TotalHousT end)
       + (case when TotalHousW is null then 0 else TotalHousW end)
       + (case when TotalHousTH is null then 0 else TotalHousTH end)
       + (case when TotalHousF is null then 0 else TotalHousF end)
       as Total
From LeaveRequest

How to get the path of running java program

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

Determine Whether Integer Is Between Two Other Integers?

There are two ways to compare three integers and check whether b is between a and c:

if a < b < c:
    pass

and

if a < b and b < c:
    pass

The first one looks like more readable, but the second one runs faster.

Let's compare using dis.dis:

>>> dis.dis('a < b and b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               0 (<)
              6 JUMP_IF_FALSE_OR_POP    14
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
        >>   14 RETURN_VALUE
>>> dis.dis('a < b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               0 (<)
             10 JUMP_IF_FALSE_OR_POP    18
             12 LOAD_NAME                2 (c)
             14 COMPARE_OP               0 (<)
             16 RETURN_VALUE
        >>   18 ROT_TWO
             20 POP_TOP
             22 RETURN_VALUE
>>>

and using timeit:

~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop

~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop

also, you may use range, as suggested before, however it is much more slower.

What tools do you use to test your public REST API?

http://www.quadrillian.com/ this enables you to create an entire test suite for your API and run it from your browser and share it with others.

IndexOf function in T-SQL

I believe you want to use CHARINDEX. You can read about it here.

How do I remove my IntelliJ license in 2019.3?

To remove the license key:

  1. Find the IntelliJ configuration directory
  2. Find the .key license file
  3. Remove or rename the .key license file

In my case on a Windows 7 machine I could find this license key in C:\Users\you\.IntelliJIdea13\config\idea13.key

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

Please use an inner query inside of the in-clause:

select col1, col2, col3... from table1
 where id in (select id from table2 where conditions...)

jQuery .live() vs .on() method for adding a click event after loading dynamic html

The equivalent of .live() in 1.7 looks like this:

$(document).on('click', '#child', function() ...); 

Basically, watch the document for click events and filter them for #child.

C# Ignore certificate errors?

IgnoreBadCertificates Method:

//I use a method to ignore bad certs caused by misc errors
IgnoreBadCertificates();

// after the Ignore call i can do what ever i want...
HttpWebRequest request_data = System.Net.WebRequest.Create(urlquerystring) as HttpWebRequest;

/*
and below the Methods we are using...
*/

/// <summary>
/// Together with the AcceptAllCertifications method right
/// below this causes to bypass errors caused by SLL-Errors.
/// </summary>
public static void IgnoreBadCertificates()
{
    System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
}  

/// <summary>
/// In Short: the Method solves the Problem of broken Certificates.
/// Sometime when requesting Data and the sending Webserverconnection
/// is based on a SSL Connection, an Error is caused by Servers whoes
/// Certificate(s) have Errors. Like when the Cert is out of date
/// and much more... So at this point when calling the method,
/// this behaviour is prevented
/// </summary>
/// <param name="sender"></param>
/// <param name="certification"></param>
/// <param name="chain"></param>
/// <param name="sslPolicyErrors"></param>
/// <returns>true</returns>
private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
} 

HTML checkbox onclick called in Javascript

You can also extract the event code from the HTML, like this :

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" />
<label for="check_all_1">Select All</label>

<script>
function selectAll(frmElement, chkElement) {
    // ...
}
document.getElementById("check_all_1").onclick = function() {
    selectAll(document.wizard_form, this);
}
</script>

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

Most efficient way to map function over numpy array

It seems no one has mentioned a built-in factory method of producing ufunc in numpy package: np.frompyfunc which I have tested again np.vectorize and have outperformed it by about 20~30%. Of course it will perform well as prescribed C code or even numba(which I have not tested), but it can a better alternative than np.vectorize

f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit vf(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. See the documentation also here

How to load/reference a file as a File instance from the classpath

Or use directly the InputStream of the resource using the absolute CLASSPATH path (starting with the / slash character):


getClass().getResourceAsStream("/com/path/to/file.txt");

Or relative CLASSPATH path (when the class you are writing is in the same Java package as the resource file itself, i.e. com.path.to):


getClass().getResourceAsStream("file.txt");

"You have mail" message in terminal, os X

I was also having this issue of "You have mail" coming up every time I started Terminal.

What I discovered is this.

Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".

You can access the mail by simply using the command

mail

This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use

t

This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow key.

If you want to jump to the end of the message, use the

spacebar

If you want to abort viewing the message, use

q 

To view the next message in the queue use

n

... assuming there's more than one message.

NOTE: You need to use these commands at the mail ? command prompt. They won't work whilst you are in the process of viewing a message. Hitting n whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q to quit from that, or hit spacebar to jump to the end of the message, and then at the ? prompt, hit n.

Viewing the content of the messages in this way may help you identify what attempted to send the message(s).

You can also view a specific message by just inputting its number at the ? prompt. 3, for instance, will show you the content of the third message (if there are that many in there).

DELETING MESSAGES

Use the d command (at the ? command prompt )

d [message number]

To delete each message when you are done looking at them. For example, d 2 will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7. Or you can delete a range of messages with (for example), d 3-10. You can find the message numbers in the list of messages mail shows you.

To delete all the messages, from the mail prompt (?) use the command d *.

As per a comment on this post, you will need to use q to quit mail, which also saves any changes.

If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):

cat /var/mail/<username>

And, if you wish to delete the emails all in one hit, use this command

sudo rm /var/mail/<username>

In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.

What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.

Simply deleting the messages

If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:

sudo rm /var/mail/YOURUSERNAME

TypeScript for ... of with index / key?

Or another old school solution:

var someArray = [9, 2, 5];
let i = 0;
for (var item of someArray) {
    console.log(item); // 9,2,5
    i++;
}

C# Change A Button's Background Color

this.button2.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(190)))), ((int)(((byte)(149)))));

How to add a column in TSQL after a specific column?

solution:

This will work for tables where there are no dependencies on the changing table which would trigger cascading events. First make sure you can drop the table you want to restructure without any disastrous repercussions. Take a note of all the dependencies and column constraints associated with your table (i.e. triggers, indexes, etc.). You may need to put them back in when you are done.

STEP 1: create the temp table to hold all the records from the table you want to restructure. Do not forget to include the new column.

CREATE TABLE #tmp_myTable
(   [new_column] [int] NOT NULL, <-- new column has been inserted here!
    [idx] [bigint] NOT NULL,
    [name] [nvarchar](30) NOT NULL,
    [active] [bit] NOT NULL
)

STEP 2: Make sure all records have been copied over and that the column structure looks the way you want.

SELECT TOP 10 * FROM #tmp_myTable ORDER BY 1 DESC -- you can do COUNT(*) or anything to make sure you copied all the records

STEP 3: DROP the original table:

DROP TABLE myTable

If you are paranoid about bad things could happen, just rename the original table (instead of dropping it). This way it can be always returned back.

EXEC sp_rename myTable, myTable_Copy

STEP 4: Recreate the table myTable the way you want (should match match the #tmp_myTable table structure)

CREATE TABLE myTable
(   [new_column] [int] NOT NULL,
    [idx] [bigint] NOT NULL,
    [name] [nvarchar](30) NOT NULL,
    [active] [bit] NOT NULL
)

-- do not forget any constraints you may need

STEP 5: Copy the all the records from the temp #tmp_myTable table into the new (improved) table myTable.

INSERT INTO myTable ([new_column],[idx],[name],[active])
SELECT [new_column],[idx],[name],[active]
FROM #tmp_myTable

STEP 6: Check if all the data is back in your new, improved table myTable. If yes, clean up after yourself and DROP the temp table #tmp_myTable and the myTable_Copy table if you chose to rename it instead of dropping it.

jQuery select all except first

$("div.test:not(:first)").hide();

or:

$("div.test:not(:eq(0))").hide();

or:

$("div.test").not(":eq(0)").hide();

or:

$("div.test:gt(0)").hide();

or: (as per @Jordan Lev's comment):

$("div.test").slice(1).hide();

and so on.

See:

Laravel Eloquent inner join with multiple conditions

//You may use this example. Might be help you...

$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
        ->join("items","items.user_id","=","users.id")
        ->join("jobs",function($join){
            $join->on("jobs.user_id","=","users.id")
                ->on("jobs.item_id","=","items.id");
        })
        ->get();
print_r($user);

How to delete only the content of file in python

I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat contains:

"This is the original content"

Then you can simply write:

f = open('myfile.dat', 'w')
f.close()

This would erase all the content. Then you can write the new content to the file:

f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()

Add text to Existing PDF using Python

pdfrw will let you read in pages from an existing PDF and draw them to a reportlab canvas (similar to drawing an image). There are examples for this in the pdfrw examples/rl1 subdirectory on github. Disclaimer: I am the pdfrw author.

How to get an element's top position relative to the browser's viewport?

jQuery implements this quite elegantly. If you look at the source for jQuery's offset, you'll find this is basically how it's implemented:

var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;

return {
    top: rect.top + win.pageYOffset,
    left: rect.left + win.pageXOffset
};

'this' vs $scope in AngularJS controllers

Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope), but not otherwise inside your controller constructor.

To bring back this behaviour (does anyone know why was it changed?) you can add:

return angular.extend($scope, this);

at the end of your controller function (provided that $scope was injected to this controller function).

This has a nice effect of having access to parent scope via controller object that you can get in child with require: '^myParentDirective'

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

How to run functions in parallel?

If you are a windows user and using python 3, then this post will help you to do parallel programming in python.when you run a usual multiprocessing library's pool programming, you will get an error regarding the main function in your program. This is because the fact that windows has no fork() functionality. The below post is giving a solution to the mentioned problem .

http://python.6.x6.nabble.com/Multiprocessing-Pool-woes-td5047050.html

Since I was using the python 3, I changed the program a little like this:

from types import FunctionType
import marshal

def _applicable(*args, **kwargs):
  name = kwargs['__pw_name']
  code = marshal.loads(kwargs['__pw_code'])
  gbls = globals() #gbls = marshal.loads(kwargs['__pw_gbls'])
  defs = marshal.loads(kwargs['__pw_defs'])
  clsr = marshal.loads(kwargs['__pw_clsr'])
  fdct = marshal.loads(kwargs['__pw_fdct'])
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  del kwargs['__pw_name']
  del kwargs['__pw_code']
  del kwargs['__pw_defs']
  del kwargs['__pw_clsr']
  del kwargs['__pw_fdct']
  return func(*args, **kwargs)

def make_applicable(f, *args, **kwargs):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  kwargs['__pw_name'] = f.__name__  # edited
  kwargs['__pw_code'] = marshal.dumps(f.__code__)   # edited
  kwargs['__pw_defs'] = marshal.dumps(f.__defaults__)  # edited
  kwargs['__pw_clsr'] = marshal.dumps(f.__closure__)  # edited
  kwargs['__pw_fdct'] = marshal.dumps(f.__dict__)   # edited
  return _applicable, args, kwargs

def _mappable(x):
  x,name,code,defs,clsr,fdct = x
  code = marshal.loads(code)
  gbls = globals() #gbls = marshal.loads(gbls)
  defs = marshal.loads(defs)
  clsr = marshal.loads(clsr)
  fdct = marshal.loads(fdct)
  func = FunctionType(code, gbls, name, defs, clsr)
  func.fdct = fdct
  return func(x)

def make_mappable(f, iterable):
  if not isinstance(f, FunctionType): raise ValueError('argument must be a function')
  name = f.__name__    # edited
  code = marshal.dumps(f.__code__)   # edited
  defs = marshal.dumps(f.__defaults__)  # edited
  clsr = marshal.dumps(f.__closure__)  # edited
  fdct = marshal.dumps(f.__dict__)  # edited
  return _mappable, ((i,name,code,defs,clsr,fdct) for i in iterable)

After this function , the above problem code is also changed a little like this:

from multiprocessing import Pool
from poolable import make_applicable, make_mappable

def cube(x):
  return x**3

if __name__ == "__main__":
  pool    = Pool(processes=2)
  results = [pool.apply_async(*make_applicable(cube,x)) for x in range(1,7)]
  print([result.get(timeout=10) for result in results])

And I got the output as :

[1, 8, 27, 64, 125, 216]

I am thinking that this post may be useful for some of the windows users.

Difference between 2 dates in SQLite

If you want difference in seconds

SELECT strftime('%s', '2019-12-02 12:32:53') - strftime('%s', '2019-12-02 11:32:53')

onKeyDown event not working on divs in React

You need to write it this way

<div 
    className="player"
    style={{ position: "absolute" }}
    onKeyDown={this.onKeyPressed}
    tabIndex="0"
  >

If onKeyPressed is not bound to this, then try to rewrite it using arrow function or bind it in the component constructor.

Python assigning multiple variables to same value? list behavior

The code that does what I need could be this:

# test

aux=[[0 for n in range(3)] for i in range(4)]
print('aux:',aux)

# initialization

a,b,c,d=[[0 for n in range(3)] for i in range(4)]

# changing values

a[0]=1
d[2]=5
print('a:',a)
print('b:',b)
print('c:',c)
print('d:',d)

Result:

('aux:', [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
('a:', [1, 0, 0])
('b:', [0, 0, 0])
('c:', [0, 0, 0])
('d:', [0, 0, 5])

Python subprocess/Popen with a modified environment

That depends on what the issue is. If it's to clone and modify the environment one solution could be:

subprocess.Popen(my_command, env=dict(os.environ, PATH="path"))

But that somewhat depends on that the replaced variables are valid python identifiers, which they most often are (how often do you run into environment variable names that are not alphanumeric+underscore or variables that starts with a number?).

Otherwise you'll could write something like:

subprocess.Popen(my_command, env=dict(os.environ, 
                                      **{"Not valid python name":"value"}))

In the very odd case (how often do you use control codes or non-ascii characters in environment variable names?) that the keys of the environment are bytes you can't (on python3) even use that construct.

As you can see the techniques (especially the first) used here benefits on the keys of the environment normally is valid python identifiers, and also known in advance (at coding time), the second approach has issues. In cases where that isn't the case you should probably look for another approach.

How to catch an Exception from a thread

Use Callable instead of Thread, then you can call Future#get() which throws any exception that the Callable threw.

How do I import a pre-existing Java project into Eclipse and get up and running?

In the menu go to : - File - Import - as the filter select 'Existing Projects into Workspace' - click next - browse to the project directory at 'select root directory' - click on 'finish'

How to change dataframe column names in pyspark?

There are many ways to do that:

  • Option 1. Using selectExpr.

    data = sqlContext.createDataFrame([("Alberto", 2), ("Dakota", 2)], 
                                      ["Name", "askdaosdka"])
    data.show()
    data.printSchema()
    
    # Output
    #+-------+----------+
    #|   Name|askdaosdka|
    #+-------+----------+
    #|Alberto|         2|
    #| Dakota|         2|
    #+-------+----------+
    
    #root
    # |-- Name: string (nullable = true)
    # |-- askdaosdka: long (nullable = true)
    
    df = data.selectExpr("Name as name", "askdaosdka as age")
    df.show()
    df.printSchema()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
    #root
    # |-- name: string (nullable = true)
    # |-- age: long (nullable = true)
    
  • Option 2. Using withColumnRenamed, notice that this method allows you to "overwrite" the same column. For Python3, replace xrange with range.

    from functools import reduce
    
    oldColumns = data.schema.names
    newColumns = ["name", "age"]
    
    df = reduce(lambda data, idx: data.withColumnRenamed(oldColumns[idx], newColumns[idx]), xrange(len(oldColumns)), data)
    df.printSchema()
    df.show()
    
  • Option 3. using alias, in Scala you can also use as.

    from pyspark.sql.functions import col
    
    data = data.select(col("Name").alias("name"), col("askdaosdka").alias("age"))
    data.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
  • Option 4. Using sqlContext.sql, which lets you use SQL queries on DataFrames registered as tables.

    sqlContext.registerDataFrameAsTable(data, "myTable")
    df2 = sqlContext.sql("SELECT Name AS name, askdaosdka as age from myTable")
    
    df2.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    

Array.size() vs Array.length

The .size() method is deprecated as of jQuery 1.8. Use the .length property instead

See: https://api.jquery.com/size/

VBA (Excel) Initialize Entire Array without Looping

For VBA you need to initialise in two lines.

Sub TestArray()

Dim myArray
myArray = Array(1, 2, 4, 8)

End Sub

Get HTML inside iframe using jQuery

$('#iframe').load(function() {
    var src = $('#iframe').contents().find("html").html();
    alert(src);
});

Alternative to mysql_real_escape_string without connecting to DB

Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."

With that in mind, then the function given in the second link you posted should do exactly what you need:

function mres($value)
{
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

    return str_replace($search, $replace, $value);
}

Add padding on view programmatically

view.setPadding(0,padding,0,0);

This will set the top padding to padding-pixels.

If you want to set it in dp instead, you can do a conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

OSX solution:

install latest rvm stable version

rvm get stable

use rvm command to solve the certificates automatically

rvm osx-ssl-certs update all

Is it possible to deserialize XML into List<T>?

Yes, it does deserialize to List<>. No need to keep it in an array and wrap/encapsulate it in a list.

public class UserHolder
{
    private List<User> users = null;

    public UserHolder()
    {
    }

    [XmlElement("user")]
    public List<User> Users
    {
        get { return users; }
        set { users = value; }
    }
}

Deserializing code,

XmlSerializer xs = new XmlSerializer(typeof(UserHolder));
UserHolder uh = (UserHolder)xs.Deserialize(new StringReader(str));

Running PowerShell as another user, and launching a script

You can open a new powershell window under a specified user credential like this:

start powershell -credential ""

enter image description here

get original element from ng-click

You need $event.currentTarget instead of $event.target.

Anaconda export Environment file

I find exporting the packages in string format only is more portable than exporting the whole conda environment. As the previous answer already suggested:

$ conda list -e > requirements.txt

However, this requirements.txt contains build numbers which are not portable between operating systems, e.g. between Mac and Ubuntu. In conda env export we have the option --no-builds but not with conda list -e, so we can remove the build number by issuing the following command:

$ sed -i -E "s/^(.*\=.*)(\=.*)/\1/" requirements.txt 

And recreate the environment on another computer:

conda create -n recreated_env --file requirements.txt 

Find a private field with Reflection?

Nice Syntax With Extension Method

You can access any private field of an arbitrary type with code like this:

Foo foo = new Foo();
string c = foo.GetFieldValue<string>("_bar");

For that you need to define an extension method that will do the work for you:

public static class ReflectionExtensions {
    public static T GetFieldValue<T>(this object obj, string name) {
        // Set the flags so that private and public fields from instances will be found
        var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        var field = obj.GetType().GetField(name, bindingFlags);
        return (T)field?.GetValue(obj);
    }
}

Automatic prune with Git fetch or pull

git config --global fetch.prune true

To always --prune for git fetch and git pull in all your Git repositories:

git config --global fetch.prune true

This above command appends in your global Git configuration (typically ~/.gitconfig) the following lines. Use git config -e --global to view your global configuration.

[fetch]
    prune = true

git config remote.origin.prune true

To always --prune but from one single repository:

git config remote.origin.prune true
                 #^^^^^^
                 #replace with your repo name

This above command adds in your local Git configuration (typically .git/config) the below last line. Use git config -e to view your local configuration.

[remote "origin"]
    url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    fetch = +refs/heads/*:refs/remotes/origin/*
    prune = true

You can also use --global within the second command or use instead --local within the first command.


git config --global gui.pruneDuringFetch true

If you use git gui you may also be interested by:

git config --global gui.pruneDuringFetch true

that appends:

[gui]
    pruneDuringFetch = true

References

The corresponding documentations from git help config:

--global

  For writing options: write to global ~/.gitconfig file rather than the repository .git/config, write to $XDG_CONFIG_HOME/git/config file if this file exists and the ~/.gitconfig file doesn’t.

 

--local

  For writing options: write to the repository .git/config file. This is the default behavior.

 

fetch.prune

  If true, fetch will automatically behave as if the --prune option was given on the command line. See also remote.<name>.prune.

 

gui.pruneDuringFetch

  "true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".

 

remote.<name>.prune

  When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the --prune option was given on the command line). Overrides fetch.prune settings, if any.

Android dex gives a BufferOverflowException when building

Try what van said:

Right click your projectandroid toolsandroid support library.

Hope this helps :)

Can I set an opacity only to the background image of a div?

Hello to everybody I did this and it worked well

_x000D_
_x000D_
 var canvas, ctx;_x000D_
_x000D_
  function init() {_x000D_
   canvas = document.getElementById('color');_x000D_
   ctx = canvas.getContext('2d');_x000D_
_x000D_
   ctx.save();_x000D_
   ctx.fillStyle = '#bfbfbf'; //  #00843D   // 118846_x000D_
   ctx.fillRect(0, 0, 490, 490);_x000D_
   ctx.restore();_x000D_
  }
_x000D_
section{_x000D_
  height: 400px;_x000D_
  background: url(https://images.pexels.com/photos/265087/pexels-photo-265087.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb);_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
  background-size: cover;_x000D_
  position: relative;_x000D_
 _x000D_
}_x000D_
_x000D_
canvas {_x000D_
 width: 100%;_x000D_
 height: 400px;_x000D_
 opacity: 0.9;_x000D_
_x000D_
}_x000D_
_x000D_
#text {_x000D_
 position: absolute;_x000D_
 top: 10%;_x000D_
 left: 0;_x000D_
 width: 100%;_x000D_
 text-align: center;_x000D_
}_x000D_
_x000D_
_x000D_
.middle{_x000D_
 text-align: center;_x000D_
 _x000D_
}_x000D_
_x000D_
section small{_x000D_
 background-color: #262626;_x000D_
 padding: 12px;_x000D_
 color: whitesmoke;_x000D_
  letter-spacing: 1.5px;_x000D_
_x000D_
}_x000D_
_x000D_
section i{_x000D_
  color: white;_x000D_
  background-color: grey;_x000D_
}_x000D_
_x000D_
section h1{_x000D_
  opacity: 0.8;_x000D_
}
_x000D_
<html lang="en">_x000D_
<head>_x000D_
 <meta charset="UTF-8">_x000D_
 <title>Metrics</title>_x000D_
 <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">  _x000D_
</head>  _x000D_
  _x000D_
<body onload="init();">_x000D_
<section>_x000D_
<canvas id="color"></canvas>_x000D_
_x000D_
<div class="w3-container middle" id="text">_x000D_
<i class="material-icons w3-highway-blue" style="font-size:60px;">assessment</i>_x000D_
<h1>Medimos las acciones de tus ventas y disenamos en la WEB tu Marca.</h1>_x000D_
<small>Metrics &amp; WEB</small>_x000D_
</div>_x000D_
</section> 
_x000D_
_x000D_
_x000D_

Absolute positioning ignoring padding of parent

Here is my best shot at it. I added another Div and made it red and changed you parent's height to 200px just to test it. The idea is the the child now becomes the grandchild and the parent becomes the grandparent. So the parent respects its parent. Hope you get my idea.

<html>
  <body>
    <div style="background-color: blue; padding: 10px; position: relative; height: 200px;">
     <div style="background-color: red;  position: relative; height: 100%;">    
        <div style="background-color: gray; position: absolute; left: 0px; right: 0px;bottom: 0px;">css sux</div>
     </div>
    </div>
  </body>
</html>

Edit:

I think what you are trying to do can't be done. Absolute position means that you are going to give it co-ordinates it must honor. What if the parent has a padding of 5px. And you absolutely position the child at top: -5px; left: -5px. How is it suppose to honor the parent and you at the same time??

My solution

If you want it to honor the parent, don't absolutely position it then.

Error Running React Native App From Terminal (iOS)

For any such problem:

  1. Go to .expo folder
  2. Find apk-cache
  3. Remove that folder

and you are done..

Hope it helps?

After updating Entity Framework model, Visual Studio does not see changes

If this is the bug with the edmx file located in a folder it is now fixed - download and install VS 2012 Update 1. You can get it from: http://www.microsoft.com/visualstudio/eng/downloads#d-visual-studio-2012-update

How do you create an asynchronous HTTP request in JAVA?

You may want to take a look at this question: Asynchronous IO in Java?

It looks like your best bet, if you don't want to wrangle the threads yourself is a framework. The previous post mentions Grizzly, https://grizzly.dev.java.net/, and Netty, http://www.jboss.org/netty/.

From the netty docs:

The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients.

How to show validation message below each textbox using jquery?

You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.

This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.

Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.

Your fiddle is updated, see here: jsfiddle

The code:

$('form').on('submit', function (e) {
    var focusSet = false;
    if (!$('#email').val()) {
        if ($("#email").parent().next(".validation").length == 0) // only add if not added
        {
            $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        $('#email').focus();
        focusSet = true;
    } else {
        $("#email").parent().next(".validation").remove(); // remove it
    }
    if (!$('#password').val()) {
        if ($("#password").parent().next(".validation").length == 0) // only add if not added
        {
            $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        if (!focusSet) {
            $("#password").focus();
        }
    } else {
        $("#password").parent().next(".validation").remove(); // remove it
    }
});  

The CSS:

    .validation
    {
      color: red;
      margin-bottom: 20px;
    }

Could not load file or assembly Exception from HRESULT: 0x80131040

Try this:

  • Edit the *.pubxml file in the PublishProfiles folder
  • set DeleteExistingFiles true
  • update all nugget packages, rebuild, republish and voila, issue resolved!

...worked for me when I had the same problem.

is there any IE8 only css hack?

I was looking for a good option for IE10 and below CSS styling (but it would work for IE8 only as well) and I came up with this idea:

<!--[if lt IE 10]><div class="column IE10-fix"><![endif]-->
<!--[if !lt IE 10]><!--><div class="column"><!--<![endif]-->

I declare my div or whatever you want with an extra class, this allows me to have extra CSS in the same stylesheet in a very readable manner.

It's W3C valid and not a weird CSS hack.

Setting width as a percentage using jQuery

Here is an alternative that worked for me:

$('div#somediv').css({'width': '70%'});

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

You can easily use Node.JS in your web app only for real-time communication. Node.JS is really powerful when it's about WebSockets. Therefore "PHP Notifications via Node.js" would be a great concept.

See this example: Creating a Real-Time Chat App with PHP and Node.js

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input fields.like below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)

input.submitted.ng-invalid
{
  border:1px solid #f00;
}

Thank you !!

Update:

We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
{
    border:1px solid #f00;
}

Adobe Acrobat Pro make all pages the same dimension

  • Open the PDF in MacOS´ Preview App
  • Chose File menu –> Export as PDF
  • In the export dialog klick the Details button an select your page size
  • Click save

All pages of the resulting document will be scaled to that size. The resulting file size is nearly identical to the original PDF, so I conclude, that image resolutions/compressions are not changed.

Hints:

  1. I am not sure whether the "Export as PDF" menu item is available by default or only if Adobe Acrobat is installed.

  2. My first trial was to use Preview App and print (!) into a new PDF, but this leads to additional margins around the page content.

Custom ImageView with drop shadow

Use this class to draw shadow on bitmaps

public class ShadowGenerator {

    // Percent of actual icon size
    private static final float HALF_DISTANCE = 0.5f;
    public static final float BLUR_FACTOR = 0.5f/48;

    // Percent of actual icon size
    private static final float KEY_SHADOW_DISTANCE = 1f/48;
    public static final int KEY_SHADOW_ALPHA = 61;

    public static final int AMBIENT_SHADOW_ALPHA = 30;

    private static final Object LOCK = new Object();
    // Singleton object guarded by {@link #LOCK}
    private static ShadowGenerator sShadowGenerator;

    private  int mIconSize;

    private final Canvas mCanvas;
    private final Paint mBlurPaint;
    private final Paint mDrawPaint;
    private final Context mContext;

    private ShadowGenerator(Context context) {
        mContext = context;
        mIconSize = Utils.convertDpToPixel(context,63);
        mCanvas = new Canvas();
        mBlurPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBlurPaint.setMaskFilter(new BlurMaskFilter(mIconSize * BLUR_FACTOR, Blur.NORMAL));
        mDrawPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
    }

    public synchronized Bitmap recreateIcon(Bitmap icon) {
        mIconSize = Utils.convertDpToPixel(mContext,3)+icon.getWidth();
        int[] offset = new int[2];
        Bitmap shadow = icon.extractAlpha(mBlurPaint, offset);
        Bitmap result = Bitmap.createBitmap(mIconSize, mIconSize, Config.ARGB_8888);
        mCanvas.setBitmap(result);

        // Draw ambient shadow
        mDrawPaint.setAlpha(AMBIENT_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1], mDrawPaint);

        // Draw key shadow
        mDrawPaint.setAlpha(KEY_SHADOW_ALPHA);
        mCanvas.drawBitmap(shadow, offset[0], offset[1] + KEY_SHADOW_DISTANCE * mIconSize, mDrawPaint);

        // Draw the icon
        mDrawPaint.setAlpha(255);
        mCanvas.drawBitmap(icon, 0, 0, mDrawPaint);

        mCanvas.setBitmap(null);
        return result;
    }



    public static ShadowGenerator getInstance(Context context) {

        synchronized (LOCK) {
            if (sShadowGenerator == null) {
                sShadowGenerator = new ShadowGenerator(context);
            }
        }
        return sShadowGenerator;
    }

}

Best practice for partial updates in a RESTful service

You basically have two options:

  1. Use PATCH (but note that you have to define your own media type that specifies what will happen exactly)

  2. Use POST to a sub resource and return 303 See Other with the Location header pointing to the main resource. The intention of the 303 is to tell the client: "I have performed your POST and the effect was that some other resource was updated. See Location header for which resource that was." POST/303 is intended for iterative additions to a resources to build up the state of some main resource and it is a perfect fit for partial updates.

Write / add data in JSON file using Node.js

you should read the file, every time you want to add a new property to the json, and then add the the new properties

var fs = require('fs');
fs.readFile('data.json',function(err,content){
  if(err) throw err;
  var parseJson = JSON.parse(content);
  for (i=0; i <11 ; i++){
   parseJson.table.push({id:i, square:i*i})
  }
  fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
    if(err) throw err;
  })
})

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

Get URL of ASP.Net Page in code-behind

Use this:

Request.Url.AbsoluteUri

That will get you the full path (including http://...)

How to pass ArrayList of Objects from one to another activity using Intent in android?

The easiest way to pass ArrayList using intent

  1. Add this line in dependencies block build.gradle.

    implementation 'com.google.code.gson:gson:2.2.4'
    
  2. pass arraylist

    ArrayList<String> listPrivate = new ArrayList<>();
    
    
    Intent intent = new Intent(MainActivity.this, ListActivity.class);
    intent.putExtra("private_list", new Gson().toJson(listPrivate));
    startActivity(intent);
    
  3. retrieve list in another activity

    ArrayList<String> listPrivate = new ArrayList<>();
    
    Type type = new TypeToken<List<String>>() {
    }.getType();
    listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
    

You can use object also instead of String in type

Works for me..

Print range of numbers on same line

for i in range(1,11):
    print(i)

i know this is an old question but i think this works now

Member '<method>' cannot be accessed with an instance reference

cannot be accessed with an instance reference

It means you're calling a STATIC method and passing it an instance. The easiest solution is to remove Static, eg:

public static void ExportToExcel(IEnumerable data, string sheetName) {

TLS 1.2 in .NET Framework 4.0

Make the following changes in your Registry and it should work:

1.) .NET Framework strong cryptography registry keys

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

2.) Secure Channel (Schannel) TLS 1.2 registry keys

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

Insert null/empty value in sql datetime column by default

you can use like this:

string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

How to overcome root domain CNAME restrictions?

My company does the same thing for a number of customers where we host a web site for them although in our case it's xyz.company.com rather than www.company.com. We do get them to set the A record on xyz.company.com to point to an IP address we allocate them.

As to how you could cope with a change in IP address I don't think there is a perfect solution. Some ideas are:

  • Use a NAT or IP load balancer and give your customers an IP address belonging to it. If the IP address of the web server needs to change you could make an update on the NAT or load balancer,

  • Offer a DNS hosting service as well and get your customers to host their domain with you so that you'd be in a position to update the A records,

  • Get your customers to set their A record up to one main web server and use a HTTP redirect for each customer's web requests.

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

How to Sort a List<T> by a property in the object

An improved of Roger's version.

The problem with GetDynamicSortProperty is that only get the property names but what happen if in the GridView we use NavigationProperties? it will send an exception, since it finds null.

Example:

"Employee.Company.Name; " will crash... since allows only "Name" as a parameter to get its value.

Here's an improved version that allows us to sort by Navigation Properties.

public object GetDynamicSortProperty(object item, string propName)
    {
        try
        {                 
            string[] prop = propName.Split('.'); 

            //Use reflection to get order type                   
            int i = 0;                    
            while (i < prop.Count())
            {
                item = item.GetType().GetProperty(prop[i]).GetValue(item, null);
                i++;
            }                     

            return item;
        }
        catch (Exception ex)
        {
            throw ex;
        }


    } 

Uri not Absolute exception getting while calling Restful Webservice

For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.

Writing outputs to log file and console

I tried joonty's answer, but I also got the

exec: 1: not found

error. This is what works best for me (confirmed to work in zsh also):

#!/bin/bash
LOG_FILE=/tmp/both.log
exec > >(tee ${LOG_FILE}) 2>&1
echo "this is stdout"
chmmm 77 /makeError

The file /tmp/both.log afterwards contains

this is stdout
chmmm command not found 

The /tmp/both.log is appended unless you remove the -a from tee.

Hint: >(...) is a process substitution. It lets the exec to the tee command as if it were a file.

Unicode via CSS :before

The code points used in icon font tricks are usually Private Use code points, which means that they have no generally defined meaning and should not be used in open information interchange, only by private agreement between interested parties. However, Private Use code points can be represented as any other Unicode value, e.g. in CSS using a notation like \f066, as others have answered. You can even enter the code point as such, if your document is UTF-8 encoded and you know how to type an arbitrary Unicode value by its number in your authoring environment (but of course it would normally be displayed using a symbol for an unknown character).

However, this is not the normal way of using icon fonts. Normally you use a CSS file provided with the font and use constructs like <span class="icon-resize-small">foo</span>. The CSS code will then take care of inserting the symbol at the start of the element, and you don’t need to know the code point number.

Calculating the sum of two variables in a batch script

@ECHO OFF
ECHO Welcome to my calculator!
ECHO What is the number you want to insert to find the sum?
SET /P Num1=
ECHO What is the second number? 
SET /P Num2=
SET /A Ans=%Num1%+%Num2%
ECHO The sum is: %Ans%
PAUSE>NUL

Proper way to catch exception from JSON.parse

I am fairly new to Javascript. But this is what I understood: JSON.parse() returns SyntaxError exceptions when invalid JSON is provided as its first parameter. So. It would be better to catch that exception as such like as follows:

try {
    let sData = `
        {
            "id": "1",
            "name": "UbuntuGod",
        }
    `;
    console.log(JSON.parse(sData));
} catch (objError) {
    if (objError instanceof SyntaxError) {
        console.error(objError.name);
    } else {
        console.error(objError.message);
    }
}

The reason why I made the words "first parameter" bold is that JSON.parse() takes a reviver function as its second parameter.

Specifying Style and Weight for Google Fonts

font-family:'Open Sans' , sans-serif;

For light: font-weight : 100; Or font-weight : lighter;

For normal: font-weight : 500; Or font-weight : normal;

For bold: font-weight : 700; Or font-weight : bold;

For more bolder: font-weight : 900; Or font-weight : bolder;

How to add a custom Ribbon tab using VBA?

I was able to accomplish this with VBA in Excel 2013. No special editors needed. All you need is the Visual Basic code editor which can be accessed on the Developer tab. The Developer tab is not visible by default so it needs to be enabled in File>Options>Customize Ribbon. On the Developer tab, click the Visual Basic button. The code editor will launch. Right click in the Project Explorer pane on the left. Click the insert menu and choose module. Add both subs below to the new module.

Sub LoadCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI      xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + "  <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "      <mso:tab id='reportTab' label='Reports' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + "        <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <mso:button id='runReport' label='PTO' "   & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3'      onAction='GenReport'/>" & vbNewLine
ribbonXML = ribbonXML + "        </mso:group>" & vbNewLine
ribbonXML = ribbonXML + "      </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + "    </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "  </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Sub ClearCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI           xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Call LoadCustRibbon sub in the Wookbook open even and call the ClearCustRibbon sub in the Before_Close Event of the ThisWorkbook code file.

How do I run a spring boot executable jar in a Production environment?

My Spring boot application has two initializers. One for development and another for production. For development, I use the main method like this:

@SpringBootApplication
public class MyAppInitializer {

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

}

My Initializer for production environment extends the SpringBootServletInitializer and looks like this:

@SpringBootApplication
public class MyAppInitializerServlet extends SpringBootServletInitializer{
    private static final Logger log = Logger
            .getLogger(SpringBootServletInitializer.class);
    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder builder) {
        log.trace("Initializing the application");
        return builder.sources(MyAppInitializerServlet .class);
    }

}

I use gradle and my build.gradle file applies 'WAR' plugin. When I run it in the development environment, I use bootrun task. Where as when I want to deploy it to production, I use assemble task to generate the WAR and deploy.

I can run like a normal spring application in production without discounting the advantages provided by the inbuilt tomcat while developing. Hope this helps.

Creating a range of dates in Python

A bit of a late answer I know, but I just had the same problem and decided that Python's internal range function was a bit lacking in this respect so I've overridden it in a util module of mine.

from __builtin__ import range as _range
from datetime import datetime, timedelta

def range(*args):
    if len(args) != 3:
        return _range(*args)
    start, stop, step = args
    if start < stop:
        cmp = lambda a, b: a < b
        inc = lambda a: a + step
    else:
        cmp = lambda a, b: a > b
        inc = lambda a: a - step
    output = [start]
    while cmp(start, stop):
        start = inc(start)
        output.append(start)

    return output

print range(datetime(2011, 5, 1), datetime(2011, 10, 1), timedelta(days=30))

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

I had trouble with the accepted answer (because I missed the HorizontalAlignment=Stretch portion and have adjusted the original answer).

This is another technique. It uses a Grid with a SharedSizeGroup.

Note: the Grid.IsSharedScope=true on the ListView.

<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}" Grid.IsSharedSizeScope="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" Width="40">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                             <Grid>
                                  <Grid.ColumnDefinitions>
                                       <ColumnDefinition Width="Auto" SharedSizeGroup="IdColumn"/>
                                  </Grid.ColumnDefinitions>
                                  <TextBlock HorizontalAlignment="Right" Text={Binding Path=Id}"/>
                             </Grid>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" />
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

angular2 manually firing click event on particular element

Angular4

Instead of

    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);

use

    this.fileInput.nativeElement.dispatchEvent(event);

because invokeElementMethod won't be part of the renderer anymore.

Angular2

Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke dispatchEvent to fire the event:

import { Component, Renderer, ElementRef, ViewChild } from '@angular/core';
@Component({
  ...
  template: `
...
<input #fileInput type="file" id="imgFile" (click)="onChange($event)" >
...`
})
class MyComponent {
  @ViewChild('fileInput') fileInput:ElementRef;

  constructor(private renderer:Renderer) {}

  showImageBrowseDlg() {
    // from http://stackoverflow.com/a/32010791/217408
    let event = new MouseEvent('click', {bubbles: true});
    this.renderer.invokeElementMethod(
        this.fileInput.nativeElement, 'dispatchEvent', [event]);
  }
}

Update

Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well

this.fileInput.nativeElement.click()

See also https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

how to place last div into right top corner of parent div? (css)

If you can add another wrapping div "block3" you could do something like this.

 <html>
      <head>
      <style type="text/css">
      .block1 {color:red;width:120px;border:1px solid green; height: 100px;}
      .block3 {float:left; width:10px;}
      .block2 {color:blue;width:70px;border:2px solid black;position:relative;float:right;}
      </style>
      </head>

    <body>
    <div class='block1'>

        <div class='block3'>
            <p>text1</p>
            <p>text2</p>
        </div>

        <div class='block2'>block2</DIV>

    </div>

    </body>
    </html>

How to change the bootstrap primary color?

Yes, I'd suggest opening up the .css file, inspect the page and find the color code you want to change and Find All and Replace (depending on your text editor) to the color you want. Do that with all the colors you want to change

How to make zsh run as a login shell on Mac OS X (in iTerm)?

The command to change the shell at startup is chsh -s <path_to_shell>. The default shells in mac OS X are installed inside the bin directory so if you want to change to the default zsh then you would use the following

chsh -s /bin/zsh

If you're using different version of zsh then you might have to add that version to /etc/shells to avoid the nonstandard shell message. For example if you want home-brew's version of zsh then you have to add /usr/local/bin/zsh to the aforementioned file which you can do in one command sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" and then run

chsh -s /usr/local/bin/zsh

Or if you want to do the whole thing in one command just copy and paste this if you have zsh already installed

sudo sh -c "echo '/usr/local/bin/zsh' >> /etc/shells" && chsh -s /usr/local/bin/zsh

Checking Bash exit status of several commands efficiently

For what it's worth, a shorter way to write code to check each command for success is:

command1 || echo "command1 borked it"
command2 || echo "command2 borked it"

It's still tedious but at least it's readable.

How to add a delay for a 2 or 3 seconds

System.Threading.Thread.Sleep(
    (int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);

Or with using statements:

Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);

I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

.Contains() on a list of custom class objects

If you want to have control over this you need to implement the [IEquatable interface][1]

[1]: http://This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).

Calling a function from a string in C#

Yes. You can use reflection. Something like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

Why is it important to override GetHashCode when Equals method is overridden?

It is because the framework requires that two objects that are the same must have the same hashcode. If you override the equals method to do a special comparison of two objects and the two objects are considered the same by the method, then the hash code of the two objects must also be the same. (Dictionaries and Hashtables rely on this principle).

How do I get the MAX row with a GROUP BY in LINQ query?

In methods chain form:

db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
    {
        Serial_Number = g.Key,
        uid = g.Max(row => row.uid)
    });

Prevent Caching in ASP.NET MVC for specific actions using an attribute

Correct attribute value for Asp.Net MVC Core to prevent browser caching (including Internet Explorer 11) is:

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

as described in Microsoft documentation:

Response caching in ASP.NET Core - NoStore and Location.None

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

Delimiters, delimiters...

You really need them when there are multiple statements in your procedure. (in other words, do you have a ; in your code and then more statements/commands? Then, you need to use delimiters).

For such a simpler rpocedure as yours though, you could just do:

CREATE PROCEDURE ProG()
  SELECT * FROM `hs_hr_employee_leave_quota`;

Circle drawing with SVG's arc path

It's a good idea that using two arc command to draw a full circle.

usually, I use ellipse or circle element to draw a full circle.

Is there a free GUI management tool for Oracle Database Express?

You could try this: it's a very good tool, very fast and effective.

http://code.google.com/p/oracle-gui/

What happens to C# Dictionary<int, int> lookup if the key does not exist?

The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key.

As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective.

This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.

How to have the cp command create any necessary folders for copying a file to a destination

cp -Rvn /source/path/* /destination/path/
cp: /destination/path/any.zip: No such file or directory

It will create no existing paths in destination, if path have a source file inside. This dont create empty directories.

A moment ago i've seen xxxxxxxx: No such file or directory, because i run out of free space. without error message.

with ditto:

ditto -V /source/path/* /destination/path
ditto: /destination/path/any.zip: No space left on device

once freed space cp -Rvn /source/path/* /destination/path/ works as expected

date format yyyy-MM-ddTHH:mm:ssZ

In C# 6+ you can use string interpolation and make this more terse:

$"{DateTime.UtcNow:s}Z"

How to delete the first row of a dataframe in R?

While I agree with the most voted answer, here is another way to keep all rows except the first:

dat <- tail(dat, -1)

This can also be accomplished using Hadley Wickham's dplyr package.

dat <- dat %>% slice(-1)

Vagrant error : Failed to mount folders in Linux guest

I was running Vagrant with VirtualBox 5.1.X, and had to downgrade to VirtualBox 5.0.40, and install the vbguest plugin to solve this problem.

My steps were:

  • Uninstall VirtualBox 5.1.X
  • Install Vagrant 5.0.40
  • Reboot my machine
  • Run vagrant up for my vagrant. It'll fail.
  • Run vagrant plugin install vagrant-vbguest while my VM is running, to install the vagrant plugin. This manages syncing VirtualBox Guest versions between host and guest.
  • Run vagrant reload to reload my virtual machine
  • Magic!

How to get the changes on a branch in Git

What you want to see is the list of outgoing commits. You can do this using

git log master..branchName 

or

git log master..branchName --oneline

Where I assume that "branchName" was created as a tracking branch of "master".

Similarly, to see the incoming changes you can use:

git log branchName..master

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

How to match "any character" in regular expression?

I work this Not always dot is means any char. Exception when single line mode. \p{all} should be

String value = "|°¬<>!\"#$%&/()=?'\\¡¿/*-+_@[]^^{}";
String expression = "[a-zA-Z0-9\\p{all}]{0,50}";
if(value.matches(expression)){
    System.out.println("true");
} else {
    System.out.println("false");
}

BeautifulSoup Grab Visible Webpage Text

import urllib
from bs4 import BeautifulSoup

url = "https://www.yahoo.com"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# kill all script and style elements
for script in soup(["script", "style"]):
    script.extract()    # rip it out

# get text
text = soup.get_text()

# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text.encode('utf-8'))

tar: add all files and directories in current directory INCLUDING .svn and so on

Had a similar situation myself. I think it is best to create the tar elsewhere and then use -C to tell tar the base directory for the compressed files. Example:

tar -cjf workspace.tar.gz -C <path_to_workspace> $(ls -A <path_to_workspace>)

This way there is no need to exclude your own tarfile. As noted in other comments, -A will list hidden files.

How to set iframe size dynamically

If you use jquery, it can be done by using $(window).height();

<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>

<script type="text/javascript" language="javascript"> 
$('.myIframe').css('height', $(window).height()+'px');
</script>

Using set_facts and with_items together in Ansible

Jinja 2.6 does not have the map function. So an alternate way of doing this would be:

set_fact: foo="{% for i in bar_result.results %}{{ i.ansible_facts.foo_item }}{%endfor%}"

Maximum number of rows in an MS Access database engine table?

As others have stated it's combination of your schema and the number of indexes.

A friend had about 100,000,000 historical stock prices, daily closing quotes, in an MDB which approached the 2 Gb limit.

He pulled them down using some code found in a Microsoft Knowledge base article. I was rather surprised that whatever server he was using didn't cut him off after the first 100K records.

He could view any record in under a second.

How to escape a JSON string to have it in a URL?

Using encodeURIComponent():

var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),

How can I view the allocation unit size of a NTFS partition in Vista?

The value for BYTES PER CLUSTER - 65536 = 64K

C:\temp>fsutil fsinfo drives

Drives: C:\ D:\ E:\ F:\ G:\ I:\ J:\ N:\ O:\ P:\ S:\

C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number :       0xfe5a90935a9049f3
NTFS Version   :                  3.1
LFS Version    :                  2.0
Number Sectors :                  0x00000002e15befff
Total Clusters :                  0x000000005c2b7dff
Free Clusters  :                  0x000000005c2a15f0
Total Reserved :                  0x0000000000000000
Bytes Per Sector  :               512
Bytes Per Physical Sector :       512
Bytes Per Cluster :               4096
Bytes Per FileRecord Segment    : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length :           0x0000000000040000
Mft Start Lcn  :                  0x00000000000c0000
Mft2 Start Lcn :                  0x0000000000000002
Mft Zone Start :                  0x00000000000c0000
Mft Zone End   :                  0x00000000000cc820
Resource Manager Identifier :     560F51B2-CEFA-11E5-80C9-98BE94F91273

C:\temp>fsutil fsinfo ntfsInfo N:
NTFS Volume Serial Number :       0x36acd4b1acd46d3d
NTFS Version   :                  3.1
LFS Version    :                  2.0
Number Sectors :                  0x00000002e15befff
Total Clusters :                  0x0000000005c2b7df
Free Clusters  :                  0x0000000005c2ac28
Total Reserved :                  0x0000000000000000
Bytes Per Sector  :               512
Bytes Per Physical Sector :       512
Bytes Per Cluster :               65536
Bytes Per FileRecord Segment    : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length :           0x0000000000010000
Mft Start Lcn  :                  0x000000000000c000
Mft2 Start Lcn :                  0x0000000000000001
Mft Zone Start :                  0x000000000000c000
Mft Zone End   :                  0x000000000000cca0
Resource Manager Identifier :     560F51C3-CEFA-11E5-80C9-98BE94F91273

Upload Progress Bar in PHP

You would need to use Javascript to create a progress bar. A simple Google search led me to this article: WebAppers Simple Javascript Progress Bar with CSS.

Dojo File Upload Progress Bar Widget is another option using the Dojo Javascript framework.

EDIT: Assuming your uploading a large number of images (such as a photo album), and POSTing them to your PHP script, you could use javascript to read the results back from the post and update the progress bar based on the number of images uploaded / total number of images. This has the side effect of only updating after each post has completed. Check out here for some info on how to post with JS.

iOS change navigation bar title font and color

Here is an answer for your question:

Move your code to below method because navigation bar title updated after view loaded. I tried adding above code in viewDidLoad doesn't work, it works fine in viewDidAppear method.

  -(void)viewDidAppear:(BOOL)animated{}

How do I declare a namespace in JavaScript?

In JavaScript there are no predefined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. Here is a procedure we follow in Oodles technologies.

Register a NameSpace Following is the function to register a name space

//Register NameSpaces Function
function registerNS(args){
 var nameSpaceParts = args.split(".");
 var root = window;

 for(var i=0; i < nameSpaceParts.length; i++)
 {
  if(typeof root[nameSpaceParts[i]] == "undefined")
   root[nameSpaceParts[i]] = new Object();

  root = root[nameSpaceParts[i]];
 }
}

To register a Namespace just call the above function with the argument as name space separated by '.' (dot). For Example Let your application name is oodles. You can make a namespace by following method

registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;

Basically it will create your NameSpaces structure like below in backend:

var oodles = {
    "HomeUtilities": {},
    "GlobalUtilities": {}
};

In the above function you have register a namespace called "oodles.HomeUtilities" and "oodles.GlobalUtilities". To call these namespaces we make an variable i.e. var $OHU and var $OGU.

These variables are nothing but an alias to Intializing the namespace. Now, Whenever you declare a function that belong to HomeUtilities you will declare it like following:

$OHU.initialization = function(){
    //Your Code Here
};

Above is the function name initialization and it is put into an namespace $OHU. and to call this function anywhere in the script files. Just use following code.

$OHU.initialization();

Similarly, with the another NameSpaces.

Hope it helps.

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

You may want to comment out the DL is deprecated, please use Fiddle warning at

C:\Ruby200\lib\ruby\2.0.0\dl.rb

since it’s annoying and you are not the irb/pry or some other gems code owner

How to tell which disk Windows Used to Boot

There is no boot.ini on a machine with just Vista installed.

How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\, d:) or by how its hardware signature (which bus, etc).

For the simple case check out GetSystemDirectory

anchor jumping by using javascript

I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.

On the .html file I have:

<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>

On the .js file I have

function myFunction() {
    var input = prompt("list or new or quit");

    while(input !== "quit") {
        if(input ==="test100") {
            window.location.hash = 'test100';
            return;
// else if(input.indexOf("test100") >= 0) {
//   window.location.hash = 'test100';
//   return;
// }
        }
    }
}

When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.

I use Google Chrome.

Note: This idea comes from linking on the same page using

<a href="#test100">Test link</a>

which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.

Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?

comparing elements of the same array in java

Try this or purpose will solve with lesser no of steps

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

How to pass arguments to a Button command in Tkinter?

This can also be done by using partial from the standard library functools, like this:

from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)