Programs & Examples On #Dockable

How do I REALLY reset the Visual Studio window layout?

I had similar problem except that it happened without installing any plugin. I begin to get this dialog about source control every time I open the project + tons of windows popping up and floating which I had to close one by one.

enter image description here

Windows -> Rest Windows Layout, fixed it for me without any problems. It does bring the default setting which I don't mind at all :)

List all employee's names and their managers by manager name using an inner join

Your query is close you need to join using the mgr and the empid

on e1.mgr = e2.empid

So the full query is:

select e1.ename Emp,
  e2.eName Mgr
from employees e1
inner join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

If you want to return all rows including those without a manager then you would change it to a LEFT JOIN (for example the president):

select e1.ename Emp,
  e2.eName Mgr
from employees e1
left join employees e2
  on e1.mgr = e2.empid

See SQL Fiddle with Demo

The president in your sample data will return a null value for the manager because they do not have a manager.

Converting Swagger specification JSON to HTML documentation

Everything was too difficult or badly documented so I solved this with a simple script swagger-yaml-to-html.py, which works like this

python swagger-yaml-to-html.py < /path/to/api.yaml > doc.html

This is for YAML but modifying it to work with JSON is also trivial.

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

I guess if you change the id_no, some of the foreign keys would not reference anything, thus the constraint violation. You could add initialy deffered to the foreign keys, so the constraints are checked when the changes are commited

Predicate in Java

Adding up to what Micheal has said:

You can use Predicate as follows in filtering collections in java:

public static <T> Collection<T> filter(final Collection<T> target,
   final Predicate<T> predicate) {
  final Collection<T> result = new ArrayList<T>();
  for (final T element : target) {
   if (predicate.apply(element)) {
    result.add(element);
   }
  }
  return result;
}

one possible predicate can be:

final Predicate<DisplayFieldDto> filterCriteria = 
                    new Predicate<DisplayFieldDto>() {
   public boolean apply(final DisplayFieldDto displayFieldDto) {
    return displayFieldDto.isDisplay();
   }
  };

Usage:

 final List<DisplayFieldDto> filteredList=
 (List<DisplayFieldDto>)filter(displayFieldsList, filterCriteria);

How to use css style in php

I had this problem just now and I tried the require_once trick, but it would just echo the CSS above all my php code without actually applying the styles.

What I did to fix it, though, was wrap all my php in their own plain HTML templates. Just type out html in the first line of the document and pick the suggestion html:5 to get the HTML boilerplate, like you would when you're just starting a plain HTML doc. Then cut the closing body and html tags and paste them all the way down at the bottom, below the closing php tag to wrap your php code without actually changing anything. Finally, you can just put your plain old link to your stylesheet into the head of your HTML. Works just fine.

White space at top of page

overflow: auto

Using overflow: auto on the <body> tag is a cleaner solution and will work a charm.

how to convert date to a format `mm/dd/yyyy`

As your data already in varchar, you have to convert it into date first:

select convert(varchar(10), cast(ts as date), 101) from <your table>

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :

--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT  CONNECT ON DATABASE nova  TO user;

--ACCESS SCHEMA
REVOKE ALL     ON SCHEMA public FROM PUBLIC;
GRANT  USAGE   ON SCHEMA public  TO user;

--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

What is “2's Complement”?

2’s Complements: When we add an extra one with the 1’s complements of a number we will get the 2’s complements. For example: 100101 it’s 1’s complement is 011010 and 2’s complement is 011010+1 = 011011 (By adding one with 1's complement) For more information this article explain it graphically.

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

get basic SQL Server table structure information

You could use these functions:

sp_help TableName
sp_helptext ProcedureName

How to find duplicate records in PostgreSQL

From "Find duplicate rows with PostgreSQL" here's smart solution:

select * from (
  SELECT id,
  ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
  FROM tbl
) dups
where 
dups.Row > 1

Setting the MySQL root user password on OS X

When I installed OS X Yosemite,I got problem with Mysql. I tried lot of methods but none worked. I actually found a quite easy way. Try this out.

  1. First log in terminal from su privileges.

sudo su

  1. stop mysql

sudo /usr/local/mysql/support-files/mysql.server stop

  1. start in safe mode:

sudo mysqld_safe --skip-grant-tables

  1. open another terminal, log in as su privileges than, log in mysql without password

mysql -u root

  1. change the password

UPDATE mysql.user SET Password=PASSWORD('new_password') WHERE User='root';

  1. flush privileges

FLUSH PRIVILEGES;

  1. You are done now

Pass mouse events through absolutely-positioned element

pointer-events: none;

Is a CSS property that makes events "pass through" the element to which it is applied and makes the event occur on the element "below".

See for details: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

It is not supported up to IE 11; all other vendors support it since quite some time (global support was ~92% in 12/'16): http://caniuse.com/#feat=pointer-events (thanks to @s4y for providing the link in the comments).

PowerShell equivalent to grep -f

So I found a pretty good answer at this link: https://www.thomasmaurer.ch/2011/03/powershell-search-for-string-or-grep-for-powershell/

But essentially it is:

Select-String -Path "C:\file\Path\*.txt" -Pattern "^Enter REGEX Here$"

This gives a directory file search (*or you can just specify a file) and a file-content search all in one line of PowerShell, very similar to grep. The output will be similar to:

doc.txt:31: Enter REGEX Here
HelloWorld.txt:13: Enter REGEX Here

How to use HTML to print header and footer on every printed page of a document?

I'm surprised and unimpressed that Chrome has such terrible CSS print support.

My task required showing a slightly different footer on each page. In the simplest case, just an incrementing chapter and page number. In more complex cases, more text in the footer - for example, several footnotes - which could expand it in size, causing what is on that page's content area to be shrunk and part of it to reflow to the next page.

CSS print cannot solve this, at least not with shoddy browser support today. But stepping outside of print, CSS3 can do a lot of the heavy lifting:

https://jsfiddle.net/b9chris/moctxd2a/29/

<div class=page>
  <header></header>
  <div class=content>Content</div>
  <footer></footer>
</div>

SCSS:

body {
  @media screen {
    width: 7.5in;
    margin: 0 auto;
  }
}

div.page {
  display: flex;
  height: 10in;    
  flex-flow: column nowrap;
  justify-content: space-between;
  align-content: stretch;
}

div.content {
  flex-grow: 1;
}

@media print {
  @page {
    size: letter;  // US 8.5in x 11in
    margin: .5in;
  }

  footer {
    page-break-after: always;
  }
}

There's a little more code in the example, including some Cat Ipsum; but the js in use is just there to demonstrate how much the header/footer can vary without breaking pagination. The key really is to take a column-bottom-sticking trick from CSS Flexbox and then apply it to a page of a known, fixed height - in this case, an 8.5"x11" piece of US letter-sized paper, with .5" margins leaving width: 7.5in and height: 10in exactly. Once the CSS flex container is told its exact dimensions (div.page), it's easy to get the header and footer to expand and contract the way they do in conventional typography.

What's left is flowing the content of the page when the footer, for example, grows to 8 footnotes not 3. In my case the content is fixed enough that I don't need to worry about it, but I'm sure there's a way to do it. One approach that leaps to mind, is to turn the header and footer into 100% width floats, then position them with Javascript. The browser will handle the interruptions to regular content flow for you automatically.

How do I make a C++ macro behave like a function?

Here is an answer coming right from the libc6! Taking a look at /usr/include/x86_64-linux-gnu/bits/byteswap.h, I found the trick you were looking for.

A few critics of previous solutions:

  • Kip's solution does not permit evaluating to an expression, which is in the end often needed.
  • coppro's solution does not permit assigning a variable as the expressions are separate, but can evaluate to an expression.
  • Steve Jessop's solution uses the C++11 auto keyword, that's fine, but feel free to use the known/expected type instead.

The trick is to use both the (expr,expr) construct and a {} scope:

#define MACRO(X,Y) \
  ( \
    { \
      register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
      std::cout << "1st arg is:" << __x << std::endl; \
      std::cout << "2nd arg is:" << __y << std::endl; \
      std::cout << "Sum is:" << (__x + __y) << std::endl; \
      __x + __y; \
    } \
  )

Note the use of the register keyword, it's only a hint to the compiler. The X and Y macro parameters are (already) surrounded in parenthesis and casted to an expected type. This solution works properly with pre- and post-increment as parameters are evaluated only once.

For the example purpose, even though not requested, I added the __x + __y; statement, which is the way to make the whole bloc to be evaluated as that precise expression.

It's safer to use void(); if you want to make sure the macro won't evaluate to an expression, thus being illegal where an rvalue is expected.

However, the solution is not ISO C++ compliant as will complain g++ -pedantic:

warning: ISO C++ forbids braced-groups within expressions [-pedantic]

In order to give some rest to g++, use (__extension__ OLD_WHOLE_MACRO_CONTENT_HERE) so that the new definition reads:

#define MACRO(X,Y) \
  (__extension__ ( \
    { \
      register int __x = static_cast<int>(X), __y = static_cast<int>(Y); \
      std::cout << "1st arg is:" << __x << std::endl; \
      std::cout << "2nd arg is:" << __y << std::endl; \
      std::cout << "Sum is:" << (__x + __y) << std::endl; \
      __x + __y; \
    } \
  ))

In order to improve my solution even a bit more, let's use the __typeof__ keyword, as seen in MIN and MAX in C:

#define MACRO(X,Y) \
  (__extension__ ( \
    { \
      __typeof__(X) __x = (X); \
      __typeof__(Y) __y = (Y); \
      std::cout << "1st arg is:" << __x << std::endl; \
      std::cout << "2nd arg is:" << __y << std::endl; \
      std::cout << "Sum is:" << (__x + __y) << std::endl; \
      __x + __y; \
    } \
  ))

Now the compiler will determine the appropriate type. This too is a gcc extension.

Note the removal of the register keyword, as it would the following warning when used with a class type:

warning: address requested for ‘__x’, which is declared ‘register’ [-Wextra]

Retrieving parameters from a URL

Btw, I was having issues using parse_qs() and getting empty value parameters and learned that you have to pass a second optional parameter 'keep_blank_values' to return a list of the parameters in a query string that contain no values. It defaults to false. Some crappy written APIs require parameters to be present even if they contain no values

for k,v in urlparse.parse_qs(p.query, True).items():
  print k

notifyDataSetChanged not working on RecyclerView

In my case, force run #notifyDataSetChanged in main ui thread will fix

public void refresh() {
        clearSelection();
        // notifyDataSetChanged must run in main ui thread, if run in not ui thread, it will not update until manually scroll recyclerview
        ((Activity) ctx).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

How do I search a Perl array for a matching string?

If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.

my @strings = qw( aAa Bbb cCC DDD eee );

my %string_lut;

# Init via slice:
@string_lut{ map uc, @strings } = ();

# or use a for loop:
#    for my $string ( @strings ) {
#        $string_lut{ uc($string) } = undef;
#    }


#Look for a string:

my $search = 'AAa';

print "'$string' ", 
    ( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
    " in the array\n";

Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar, or other requirements that can be met through normalization (like case insensitivity).

How can I get a precise time, for example in milliseconds in Objective-C?

I would NOT use mach_absolute_time() because it queries a combination of the kernel and the processor for an absolute time using ticks (probably an uptime).

What I would use:

CFAbsoluteTimeGetCurrent();

This function is optimized to correct the difference in the iOS and OSX software and hardware.

Something Geekier

The quotient of a difference in mach_absolute_time() and AFAbsoluteTimeGetCurrent() is always around 24000011.154871

Here is a log of my app:

Please note that final result time is a difference in CFAbsoluteTimeGetCurrent()'s

 2012-03-19 21:46:35.609 Rest Counter[3776:707] First Time: 353900795.609040
 2012-03-19 21:46:36.360 Rest Counter[3776:707] Second Time: 353900796.360177
 2012-03-19 21:46:36.361 Rest Counter[3776:707] Final Result Time (difference): 0.751137
 2012-03-19 21:46:36.363 Rest Counter[3776:707] Mach absolute time: 18027372
 2012-03-19 21:46:36.365 Rest Counter[3776:707] Mach absolute time/final time: 24000113.153295
 2012-03-19 21:46:36.367 Rest Counter[3776:707] -----------------------------------------------------
 2012-03-19 21:46:43.074 Rest Counter[3776:707] First Time: 353900803.074637
 2012-03-19 21:46:43.170 Rest Counter[3776:707] Second Time: 353900803.170256
 2012-03-19 21:46:43.172 Rest Counter[3776:707] Final Result Time (difference): 0.095619
 2012-03-19 21:46:43.173 Rest Counter[3776:707] Mach absolute time: 2294833
 2012-03-19 21:46:43.175 Rest Counter[3776:707] Mach absolute time/final time: 23999753.727777
 2012-03-19 21:46:43.177 Rest Counter[3776:707] -----------------------------------------------------
 2012-03-19 21:46:46.499 Rest Counter[3776:707] First Time: 353900806.499199
 2012-03-19 21:46:55.017 Rest Counter[3776:707] Second Time: 353900815.016985
 2012-03-19 21:46:55.018 Rest Counter[3776:707] Final Result Time (difference): 8.517786
 2012-03-19 21:46:55.020 Rest Counter[3776:707] Mach absolute time: 204426836
 2012-03-19 21:46:55.022 Rest Counter[3776:707] Mach absolute time/final time: 23999996.639500
 2012-03-19 21:46:55.024 Rest Counter[3776:707] -----------------------------------------------------

How to find the remainder of a division in C?

You can use the % operator to find the remainder of a division, and compare the result with 0.

Example:

if (number % divisor == 0)
{
    //code for perfect divisor
}
else
{
    //the number doesn't divide perfectly by divisor
}

Disabled form inputs do not appear in the request

Define Colors With RGBA Values

Add the Following code under style

<!DOCTYPE html>
<html>
<head>
<style>
#p7 {background-color:rgba(215,215,215,1);}
</style>
</head>
<body>
Disabled Grey none tranparent

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />

    <!-- this does not appear in request -->
    <input id="p7" type="textbox" name="Percentage" value="100" readonly="readonly"" /> 

</form>

result

SQL Server - stop or break execution of a SQL script

you could wrap your SQL statement in a WHILE loop and use BREAK if needed

WHILE 1 = 1
BEGIN
   -- Do work here
   -- If you need to stop execution then use a BREAK


    BREAK; --Make sure to have this break at the end to prevent infinite loop
END

How to commit a change with both "message" and "description" from the command line?

In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.

git rebase -i origin/master

Then, your commits will appear:

pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

Select the commit you want to reword and save.

pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

Now, you have the opportunity to add header and body, where the first line will be the header.

Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

Does Django scale?

Playing devil's advocate a little bit:

You should check the DjangoCon 2008 Keynote, delivered by Cal Henderson, titled "Why I hate Django" where he pretty much goes over everything Django is missing that you might want to do in a high traffic website. At the end of the day you have to take this all with an open mind because it is perfectly possible to write Django apps that scale, but I thought it was a good presentation and relevant to your question.

django admin - add custom form fields that are not part of the model

If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:

I never done something like this so I'm not completely sure how it will work out.

What is a NullPointerException, and how do I fix it?

In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.

When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.

Your reference is "pointing" to null, thus "Null -> Pointer".

The object lives in the VM memory space and the only way to access it is using this references. Take this example:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

And on another place in your code:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.

How do you change the width and height of Twitter Bootstrap's tooltips?

Mine where all variable lengths and a set max width would not work for me so setting my css to 100% worked like a charm.

.tooltip-inner {
    max-width: 100%;
}

Reading a key from the Web.Config using ConfigurationManager

Try using the WebConfigurationManager class instead. For example:

string userName = WebConfigurationManager.AppSettings["PFUserName"]

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.

How to make jQuery UI nav menu horizontal?

I admire all these efforts to convert a menu to a menubar because I detest trying to hack CSS. It just feels like I'm meddling with powers I can't possibly ever understand! I think it's much easier to add the menubar files available at the menubar branch of jquery ui.

I downloaded the full jquery ui css bundled file from the jquery ui download site

In the head of my document I put the jquery ui css file that contains everything (I'm on version 1.9.x at the moment) followed by the specific CSS file for the menubar widget downloaded from the menubar branch of jquery ui

<link type="text/css" href="css/jquery-ui.css" rel="stylesheet" />
<link type="text/css" href="css/jquery.ui.menubar.css" rel="stylesheet" />

Don't forget the images folder with all the little icons used by jQuery UI needs to be in the same folder as the jquery-ui.css file.

Then at the end the body I have:

<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.0.custom.min.js"></script>
<script type="text/javascript" src="js/menubar/jquery.ui.menubar.js"></script>

That's a copy of an up-to-date version of jQuery, followed by a copy of the jQuery UI file, then the menubar module downloaded from the menubar branch of jquery ui

The menubar CSS file is refreshingly short:

.ui-menubar { list-style: none; margin: 0; padding-left: 0; }
.ui-menubar-item { float: left; }
.ui-menubar .ui-button { float: left; font-weight: normal; border-top-width: 0 !important; border-bottom-width: 0 !important; margin: 0; outline: none; }
.ui-menubar .ui-menubar-link { border-right: 1px dashed transparent; border-left: 1px dashed transparent; }
.ui-menubar .ui-menu { width: 200px; position: absolute; z-index: 9999; font-weight: normal; }

but the menubar JavaScript file is 328 lines - too long to quote here. With it, you can simply call menubar() like this example:

$("#menu").menubar({
    autoExpand: true,
    menuIcon: true,
    buttons: true,
    select: select
});

As I said, I admire all the attempts to hack the menu object to turn it into a horizontal bar, but I found all of them lacked some standard feature of a horizontal menu bar. I'm not sure why this widget is not bundled with jQuery UI yet, but presumably there are still some bugs to iron out. For instance, I tried it in IE 7 Quirks Mode and the positioning was strange, but it looks great in Firefox, Safari and IE 8+.

package android.support.v4.app does not exist ; in Android studio 0.8

IN ECLIPSE LUNA I ve resolved this issue by using contet menu on my Project : ANdroid Tools > Add support Library ...

How do I schedule a task to run at periodic intervals?

timer.scheduleAtFixedRate( new Task(), 1000,3000); 

How to vertically align text in input type="text"?

input[type=text]
{
   height: 15px; 
   line-height: 15px;
}

this is correct way to set vertical-middle position.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

jQuery DatePicker with today as maxDate

http://api.jqueryui.com/datepicker/#option-maxDate

$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );

What does Include() do in LINQ?

Let's say for instance you want to get a list of all your customers:

var customers = context.Customers.ToList();

And let's assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product.

As you can see, selecting a top-level object with many related entities could result in a query that needs to pull in data from many sources. As a performance measure, Include() allows you to indicate which related entities should be read from the database as part of the same query.

Using the same example, this might bring in all of the related order headers, but none of the other records:

var customersWithOrderDetail = context.Customers.Include("Orders").ToList();

As a final point since you asked for SQL, the first statement without Include() could generate a simple statement:

SELECT * FROM Customers;

The final statement which calls Include("Orders") may look like this:

SELECT *
FROM Customers JOIN Orders ON Customers.Id = Orders.CustomerId;

How can I decrease the size of Ratingbar?

This Worked for me.
Check this image

            android:id="@+id/ratingBar"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            android:scaleX=".8"
            android:scaleY=".8"
            android:stepSize="0.5"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.543"
            app:layout_constraintStart_toEndOf="@+id/title"
            app:layout_constraintTop_toTopOf="parent" />

What is the convention for word separator in Java package names?

Anyone can use underscore _ (its Okay)

No one should use hypen - (its Bad practice)

No one should use capital letters inside package names (Bad practice)

NOTE: Here "Bad Practice" is meant for technically you are allowed to use that, but conventionally its not in good manners to write.

Source: Naming a Package(docs.oracle)

Form onSubmit determine which submit button was pressed

Bare bones, but confirmed working, example:

<script type="text/javascript">
var clicked;
function mysubmit() {
    alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
    <input type="submit" onclick="clicked='Save'" value="Save" />
    <input type="submit" onclick="clicked='Add'" value="Add" />
</form>

How can I open a Shell inside a Vim Window?

:vsp or :sp - splits vim into two instance but you cannot use :shell in only one of them.

Why not display another tab of the terminal not another tab of vim. If you like the idea you can try it: Ctrl-shift-t. and move between them with Ctrl - pageup and Ctrl - pagedown

If you want just a few shell commands you can make any shell command in vim using !

For example :!./a.out.

Json.NET serialize object with root name

Use anonymous class

Shape your model the way you want using anonymous classes:

var root = new 
{ 
    car = new 
    { 
        name = "Ford", 
        owner = "Henry"
    }
};

string json = JsonConvert.SerializeObject(root);

Split text with '\r\n'

I think the problem is in your text file. It's probably already split into too many lines and when you read it, it "adds" additional \r and/or \n characters (as they exist in file). Check your what is read into text variable.

The code below (on a local variable with your text) works fine and splits into 2 lines:

string[] stringSeparators = new string[] { "\r\n" };
string text = "somet interesting text\nsome text that should be in the same line\r\nsome text should be in another line";
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);

How to pass parameters in $ajax POST?

    function FillData() {
    var param = $("#<%= TextBox1.ClientID %>").val();
    $("#tbDetails").append("<img src='Images/loading.gif'/>");
    $.ajax({
        type: "POST",/*method type*/
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/BindDatatable",/*Target function that will be return result*/
        data: '{"data":"' + param + '"}',/*parameter pass data is parameter name param is value */
        dataType: "json",
        success: function(data) {
               alert("Success");
            }
        },
        error: function(result) {
            alert("Error");
        }
    });   
}

Google Play Services Missing in Emulator (Android 4.4.2)

If you're using Xamarin, I found a guide on their official forum explaining how to do this:

  1. Download the package from the internet. There are many sources for this, one possible source is the CyanogenMod web site.
  2. Start up the Android Player and unlock it.
  3. Drag and drop the zip file that you downloaded onto the Android Player.
  4. Restart the Android Player.

Hereafter, you might also need to update the Google Play Services from the Google Play Store.

Hope this helps for anyone else who has troubles finding the documentation.

How do I close a tkinter window?

I think you wrongly understood the quit function of Tkinter. This function does not require you to define.

First, you should modify your function as follows:

from Tkinter import *
root = Tk()
Button(root, text="Quit", command=root.quit).pack()
root.mainloop()

Then, you should use '.pyw' suffix to save this files and double-click the '.pyw' file to run your GUI, this time, you can end the GUI with a click of the Button, and you can also find that there will be no unpleasant DOS window. (If you run the '.py' file, the quit function will fail.)

Using Javascript in CSS

To facilitate potentially solving your problem given the information you've provided, I'm going to assume you're seeking dynamic CSS. If this is the case, you can use a server-side scripting language to do so. For example (and I absolutely love doing things like this):

styles.css.php:

body
 {
margin: 0px;
font-family: Verdana;
background-color: #cccccc;
background-image: url('<?php
echo 'images/flag_bg/' . $user_country . '.png';
?>');
 }

This would set the background image to whatever was stored in the $user_country variable. This is only one example of dynamic CSS; there are virtually limitless possibilities when combining CSS and server-side code. Another case would be doing something like allowing the user to create a custom theme, storing it in a database, and then using PHP to set various properties, like so:

user_theme.css.php:

body
 {
background-color: <?php echo $user_theme['BG_COLOR']; ?>;
color: <?php echo $user_theme['COLOR']; ?>;
font-family: <?php echo $user_theme['FONT']; ?>;
 }

#panel
 {
font-size: <?php echo $user_theme['FONT_SIZE']; ?>;
background-image: <?php echo $user_theme['PANEL_BG']; ?>;
 }

Once again, though, this is merely an off-the-top-of-the-head example; harnessing the power of dynamic CSS via server-side scripting can lead to some pretty incredible stuff.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

How to add a new row to datagridview programmatically

If anyone wanted to Add DataTable as a source of gridview then--

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("column1"));
dt.Columns.Add(new DataColumn("column2"));

DataRow dr = dt.NewRow();
dr[0] = "column1 Value";
dr[1] = "column2 Value";

dt.Rows.Add(dr);

dataGridView1.DataSource = dt;

How to upper case every first letter of word in a string?

public String UpperCaseWords(String line)
{
    line = line.trim().toLowerCase();
    String data[] = line.split("\\s");
    line = "";
    for(int i =0;i< data.length;i++)
    {
        if(data[i].length()>1)
            line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
        else
            line = line + data[i].toUpperCase();
    }
    return line.trim();
}

Error Message : Cannot find or open the PDB file

The PDB file is a Visual Studio specific file that has the debugging symbols for your project. You can ignore those messages, unless you're hoping to step into the code for those dlls with the debugger (which is doubtful, as those are system dlls). In other words, you can and should ignore them, as you won't have the PDB files for any of those dlls (by default at least, it turns out you can actually obtain them when debugging via the Microsoft Symbol Server). All it means is that when you set a breakpoint and are stepping through the code, you won't be able to step into any of those dlls (which you wouldn't want to do anyways).

Just for completeness, here's the official PDB description from MSDN:

A program database (PDB) file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A PDB file is created when you compile a C/C++ program with /ZI or /Zi

Also for future reference, if you want to have PDB files for your own code, you would would have to build your project with either the /ZI or /Zi options enabled (you can set them via project properties --> C/C++ --> General, then set the field for "Debug Information Format"). Not relevant to your situation, but I figured it might be useful in the future

How to split a number into individual digits in c#?

Substring and Join methods are usable for this statement.

string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;

   for (int i = 0; i < no.Length; i++)
   {
     numberArray[i] = no.Substring(counter, 1); // 1 is split length
     counter++;
   }

Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

What does $_ mean in PowerShell?

$_ is an variable which iterates over each object/element passed from the previous | (pipe).

Print Html template in Angular 2 (ng-print in Angular 2)

EDIT: updated the snippets for a more generic approach

Just as an extension to the accepted answer,

For getting the existing styles to preserve the look 'n feel of the targeted component, you can:

  1. make a query to pull the <style> and <link> elements from the top-level document

  2. inject it into the HTML string.

To grab a HTML tag:

private getTagsHtml(tagName: keyof HTMLElementTagNameMap): string
{
    const htmlStr: string[] = [];
    const elements = document.getElementsByTagName(tagName);
    for (let idx = 0; idx < elements.length; idx++)
    {
        htmlStr.push(elements[idx].outerHTML);
    }

    return htmlStr.join('\r\n');
}

Then in the existing snippet:

const printContents = document.getElementById('print-section').innerHTML;
const stylesHtml = this.getTagsHtml('style');
const linksHtml = this.getTagsHtml('link');

const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
    <html>
        <head>
            <title>Print tab</title>
            ${linksHtml}
            ${stylesHtml}
            ^^^^^^^^^^^^^ add them as usual to the head
        </head>
        <body onload="window.print(); window.close()">
            ${printContents}
        </body>
    </html>
    `
);
popupWin.document.close();

Now using existing styles (Angular components create a minted style for itself), as well as existing style frameworks (e.g. Bootstrap, MaterialDesign, Bulma) it should look like a snippet of the existing screen

How to find tag with particular text with Beautiful Soup?

Since Beautiful Soup 4.4.0. a parameter called string does the work that text used to do in the previous versions.

string is for finding strings, you can combine it with arguments that find tags: Beautiful Soup will find all tags whose .string matches your value for the string. This code finds the tags whose .string is “Elsie”:

soup.find_all("td", string="Elsie")

For more information about string have a look this section https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-string-argument

Download TS files from video stream

You would need to download all of the transport stream (.ts) files, and concatenate them into a single mpeg for playback. Transport streams such as this have associated playlist files (.m3u8) that list all of the .ts files that you need to download and concatenate. If available, there may be a secondary .m3u8 playlist that will separately list subtitle steam files (.vtt).

Load Image from javascript

Simplest load image from JS to DOM-element:

element.innerHTML += "<img src='image.jpg'></img>";

With onload event:

element.innerHTML += "<img src='image.jpg' onload='javascript:showImage();'></img>";

Return Boolean Value on SQL Select Statement

Possibly something along these lines:

SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT)
FROM dummy WHERE id = 1;

http://sqlfiddle.com/#!3/5e555/1

Delete empty rows

I believe that your problem is that you're checking for an empty string using double quotes instead of single quotes. Try just changing to:

DELETE FROM table WHERE edit_user=''

Are there inline functions in java?

Java does not provide a way to manually suggest that a method should be inlined. As @notnoop says in the comments, the inlining is typically done by the JVM at execution time.

Invoking Java main method with parameters from Eclipse

This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.

When selecting Run As..., go into the run configurations.

On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).

Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.

How to convert int to string on Arduino?

You just need to wrap it around a String object like this:

String numberString = String(n);

You can also do:

String stringOne = "Hello String";                     // using a constant String
String stringOne =  String('a');                       // converting a constant char into a String
String stringTwo =  String("This is a string");        // converting a constant string into a String object
String stringOne =  String(stringTwo + " with more");  // concatenating two strings
String stringOne =  String(13);                        // using a constant integer
String stringOne =  String(analogRead(0), DEC);        // using an int and a base
String stringOne =  String(45, HEX);                   // using an int and a base (hexadecimal)
String stringOne =  String(255, BIN);                  // using an int and a base (binary)
String stringOne =  String(millis(), DEC);             // using a long and a base

When and why to 'return false' in JavaScript?

It is used to stop the propagation of the event. You see when you have two elements both with a click event handler (for example)

-----------------------------------
| element1                        |
|   -------------------------     |
|   |element2               |     |
|   -------------------------     |
|                                 |
-----------------------------------

If you click on the inner element (element2) it will trigger a click event in both elements: 1 and 2. It is called "Event bubbling". If you want to handle the event in element2 only, then the event handler has to return false to stop the event propagation.

Another example will be the link onclick handler. If you want to stop a link form working. You can add an onclick handler and return false. To stop the event from propagating to the default handler.

Float and double datatype in Java

The Wikipedia page on it is a good place to start.

To sum up:

  • float is represented in 32 bits, with 1 sign bit, 8 bits of exponent, and 23 bits of the significand (or what follows from a scientific-notation number: 2.33728*1012; 33728 is the significand).

  • double is represented in 64 bits, with 1 sign bit, 11 bits of exponent, and 52 bits of significand.

By default, Java uses double to represent its floating-point numerals (so a literal 3.14 is typed double). It's also the data type that will give you a much larger number range, so I would strongly encourage its use over float.

There may be certain libraries that actually force your usage of float, but in general - unless you can guarantee that your result will be small enough to fit in float's prescribed range, then it's best to opt with double.

If you require accuracy - for instance, you can't have a decimal value that is inaccurate (like 1/10 + 2/10), or you're doing anything with currency (for example, representing $10.33 in the system), then use a BigDecimal, which can support an arbitrary amount of precision and handle situations like that elegantly.

How Can I Override Style Info from a CSS Class in the Body of a Page?

Either use the style attribute to add CSS inline on your divs, e.g.:

<div style="color:red"> ... </div>

... or create your own style sheet and reference it after the existing stylesheet then your style sheet should take precedence.

... or add a <style> element in the <head> of your HTML with the CSS you need, this will take precedence over an external style sheet.

You can also add !important after your style values to override other styles on the same element.

Update

Use one of my suggestions above and target the span of class style21, rather than the containing div. The style you are applying on the containing div will not be inherited by the span as it's color is set in the style sheet.

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

How to download a folder from github?

How to download a specific folder from a GitHub repo

Here a proper solution according to this post:

  • Create a directory

     mkdir github-project-name 
     cd github-project-name
    
  • Set up a git repo

     git init
     git remote add origin <URL-link of the repo>
    
  • Configure your git-repo to download only specific directories

     git config core.sparseCheckout true # enable this
    
  • Set the folder you like to be downloaded, e.g. you only want to download the doc directory from https://github.com/project-tree/master/doc

     echo "/absolute/path/to/folder" > .git/info/sparse-checkout 
    

    E.g. if you only want to download the doc directory from your master repo https://github.com/project-tree/master/doc, then your command is echo "doc" > .git/info/sparse-checkout.

  • Download your repo as usual

     git pull origin master
    

Hiding button using jQuery

jQuery offers the .hide() method for this purpose. Simply select the element of your choice and call this method afterward. For example:

$('#comanda').hide();

One can also determine how fast the transition runs by providing a duration parameter in miliseconds or string (possible values being 'fast', and 'slow'):

$('#comanda').hide('fast');

In case you want to do something just after the element hid, you must provide a callback as a parameter too:

$('#comanda').hide('fast', function() {
  alert('It is hidden now!');
});

How to copy a file to another path?

Yes. It will work: FileInfo.CopyTo Method

Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.

All other responses are correct, but since you asked for FileInfo, here's a sample:

FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten

How can I find my php.ini on wordpress?

use this in your htaccess in your server

php_value upload_max_filesize 1000M php_value post_max_size 2000M

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

How to set up tmux so that it starts up with specified windows opened?

have a look @ https://github.com/remiprev/teamocil

you can specify your structure using YAML

windows:
  - name: sample-window
    splits:
      - cmd: vim
      - cmd:
        - ipython
        width: 50
      - cmd:
        height: 25

Android Camera Preview Stretched

You must set cameraView.getLayoutParams().height and cameraView.getLayoutParams().width according to the aspect ratio you want.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I manually filled NAs by exporting the CSV then editing it and reimporting, as below.

Perhaps one of you experts might explain why this procedure worked so well (the first file had columns with data of types char, INT and num (floating point numbers)), which all became char type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).

# STEP 1:
MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
                            header=T, stringsAsFactors=FALSE)
#... STEP 2:
TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
write.csv(TestFrame, file = "TestFrame2.csv")
# ...
# STEP 3:
# I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:    
XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
                            header=T,stringsAsFactors=FALSE)

On arrival back in R, all columns had their correct measurement levels automatically recognized by R!

How to open a web page from my application?

You cannot launch a web page from an elevated application. This will raise a 0x800004005 exception, probably because explorer.exe and the browser are running non-elevated.

To launch a web page from an elevated application in a non-elevated web browser, use the code made by Mike Feng. I tried to pass the URL to lpApplicationName but that didn't work. Also not when I use CreateProcessWithTokenW with lpApplicationName = "explorer.exe" (or iexplore.exe) and lpCommandLine = url.

The following workaround does work: Create a small EXE-project that has one task: Process.Start(url), use CreateProcessWithTokenW to run this .EXE. On my Windows 8 RC this works fine and opens the web page in Google Chrome.

Transport security has blocked a cleartext HTTP

In swift 4 and xocde 10 is change the NSAllowsArbitraryLoads to Allow Arbitrary Loads. so it is going to be look like this :

<key>App Transport Security Settings</key>
<dict>
     <key>Allow Arbitrary Loads</key><true/>
</dict>

How to get featured image of a product in woocommerce

I got the solution . I tried this .

<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' );?>

    <img src="<?php  echo $image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">

Matplotlib scatter plot with different text at each data point

As a one liner using list comprehension and numpy:

[ax.annotate(x[0], (x[1], x[2])) for x in np.array([n,z,y]).T]

setup is ditto to Rutger's answer.

What is sharding and why is it important?

Sharding was originally coined by google engineers and you can see it used pretty heavily when writing applications on Google App Engine. Since there are hard limitations on the amount of resource your queries can use and because queries themselves have strict limitations, sharding is not only encouraged but almost enforced by the architecture.

Another place sharding can be used is to reduce contention on data entities. It is especially important when building scalable systems to watch out for those piece of data that are written often because they are always the bottleneck. A good solution is to shard off that specific entity and write to multile copies, then read the total. An example of this "sharded counter wrt GAE: http://code.google.com/appengine/articles/sharding_counters.html

How to check if user input is not an int value

Maybe you can try this:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}

Adding files to java classpath at runtime

Yes I believe it's possible but you might have to implement your own classloader. I have never done it but that is the path I would probably look at.

Order of execution of tests in TestNG

I've faced the same issue, the possible reason is due to parallel execution of testng and the solution is to add Priority option or simply update preserve-order="true" in your testng.xml.

<test name="Firefox Test" preserve-order="true">

How do you create a temporary table in an Oracle database?

CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';

TortoiseSVN icons overlay not showing after updating to Windows 10

For anyone using Windows 10, there's a request in Feedback Hub to get Microsoft to fix this issue. If you'd like to add a +1 to have it fixed, here's a link: https://aka.ms/Cryalp.

The link only works on Windows 10 as it needs to open Feedback Hub to get to the suggestion. The link was generated using the "Share" feature in Feedback Hub and aka.ms is an internal link shortening service used by Microsoft.

Hibernate show real SQL

Worth noting that the code you see is sent to the database as is, the queries are sent separately to prevent SQL injection. AFAIK The ? marks are placeholders that are replaced by the number params by the database, not by hibernate.

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I was doing what doug suggests ("Reset Content and Settings") which works but takes a lot of time and it is really annoying... until I recently found completely accidental another solution that is much quicker and seems to also work so far! Just hit cmd+L on your simulator or go to the simulator menu "Hardware -> Lock", which locks the screen, when you unlock the screen the app works like nothing ever happened :)

How to install and run phpize

For ubuntu with Plesk installed run apt-get install plesk-php56-dev, for other versions just change XX in phpXX (without the dot)

Pass Hidden parameters using response.sendRedirect()

TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:

  1. Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).

    Controller (your servlet)

    request.setAttribute("message", "Hello world");
    RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
    

    View (your JSP)

    Using scriptlets:

    <%
        out.println(request.getAttribute("message"));
    %>
    

    This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.

    <c:out value="${message}" />
    
  2. If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example

    Controller

    //if request is not from HttpServletRequest, you should do a typecast before
    HttpSession session = request.getSession(false);
    //save message in session
    session.setAttribute("helloWorld", "Hello world");
    response.sendRedirect("/content/test.jsp");
    

    View

    Again, showing this using scriptlets and then EL + JSTL:

    <%
        out.println(session.getAttribute("message"));
        session.removeAttribute("message");
    %>
    
    <c:out value="${sessionScope.message}" />
    <c:remove var="message" scope="session" />
    

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

Div Scrollbar - Any way to style it?

There's also the iScroll project which allows you to style the scrollbars plus get it to work with touch devices. http://cubiq.org/iscroll-4

Https to http redirect using htaccess

Attempt 2 was close to perfect. Just modify it slightly:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

How to save LogCat contents to file?

You are not getting the answer you are looking for, are you.

Two ways to do what you want:

  1. Right-click in the logcat messages window, choose select all. Then your save will be all logcat messages in that window (including the ones scrolled out of view).
  2. When focus is in logcat messages window, type control-A, this will select all messages. Then save etc. etc.

How to align form at the center of the page in html/css

Or you can just use the <center></center> tags.

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

Is there a way to get colored text in GitHubflavored Markdown?

You cannot include style directives in GFM.

The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style> is missing.

If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.

How to fetch the dropdown values from database and display in jsp

how to fetch the dropdown values from database and display in jsp:

Dynamically Fetch data from Mysql to (drop down) select option in Jsp. This post illustrates, to fetch the data from the mysql database and display in select option element in Jsp. You should know the following post before going through this post i.e :

How to Connect Mysql database to jsp.

How to create database in MySql and insert data into database. Following database is used, to illustrate ‘Dynamically Fetch data from Mysql to (drop down)

select option in Jsp’ :

id  City
1   London
2   Bangalore
3   Mumbai
4   Paris

Following codes are used to insert the data in the MySql database. Database used is “City” and username = “root” and password is also set as “root”.

Create Database city;
Use city;

Create table new(id int(4), city varchar(30));

insert into new values(1, 'LONDON');
insert into new values(2, 'MUMBAI');
insert into new values(3, 'PARIS');
insert into new values(4, 'BANGLORE');

Here is the code to Dynamically Fetch data from Mysql to (drop down) select option in Jsp:

<%@ page import="java.sql.*" %>
<%ResultSet resultset =null;%>

<HTML>
<HEAD>
    <TITLE>Select element drop down box</TITLE>
</HEAD>

<BODY BGCOLOR=##f89ggh>

<%
    try{
//Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = 
         DriverManager.getConnection
            ("jdbc:mysql://localhost/city?user=root&password=root");

       Statement statement = connection.createStatement() ;

       resultset =statement.executeQuery("select * from new") ;
%>

<center>
    <h1> Drop down box or select element</h1>
        <select>
        <%  while(resultset.next()){ %>
            <option><%= resultset.getString(2)%></option>
        <% } %>
        </select>
</center>

<%
//**Should I input the codes here?**
        }
        catch(Exception e)
        {
             out.println("wrong entry"+e);
        }
%>

</BODY>
</HTML>

enter image description here

How to calculate md5 hash of a file using javascript

With current HTML5 it should be possible to calculate the md5 hash of a binary file, But I think the step before that would be to convert the banary data BlobBuilder to a String, I am trying to do this step: but have not been successful.

Here is the code I tried: Converting a BlobBuilder to string, in HTML5 Javascript

How to trigger the window resize event in JavaScript?

With jQuery, you can try to call trigger:

$(window).trigger('resize');

Why would an Enum implement an Interface?

When creating constants in a jar file, it is often helpful to let users extend enum values. We used enums for PropertyFile keys and got stuck because nobody could add any new ones! Below would have worked much better.

Given:

public interface Color {
  String fetchName();
}

and:

public class MarkTest {

  public static void main(String[] args) {
    MarkTest.showColor(Colors.BLUE);
    MarkTest.showColor(MyColors.BROWN);
  }

  private static void showColor(Color c) {
    System.out.println(c.fetchName());
  }
}

one could have one enum in the jar:

public enum Colors implements Color {
  BLUE, RED, GREEN;
  @Override
  public String fetchName() {
    return this.name();
  }
}

and a user could extend it to add his own colors:

public enum MyColors implements Color {
  BROWN, GREEN, YELLOW;
  @Override
  public String fetchName() {
    return this.name();
  }
}

Trimming text strings in SQL Server 2008

I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.

The solution is however straight forward:

User Defined Trim Function

How to $watch multiple variable change in angular

There is many way to watch multiple values :

//angular 1.1.4
$scope.$watchCollection(['foo', 'bar'], function(newValues, oldValues){
    // do what you want here
});

or more recent version

//angular 1.3
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
  //do what you want here
});

Read official doc for more informations : https://docs.angularjs.org/api/ng/type/$rootScope.Scope

git ahead/behind info between master and branch?

After doing a git fetch, you can run git status to show how many commits the local branch is ahead or behind of the remote version of the branch.

This won't show you how many commits it is ahead or behind of a different branch though. Your options are the full diff, looking at github, or using a solution like Vimhsa linked above: Git status over all repo's

passing several arguments to FUN of lapply (and others *apply)

As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:

mapply(myfun, arg1, arg2)

See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html

How to change the background color of the options menu?

For Android 2.3 this can be done with some very heavy hacking:

The root cause for the issues with Android 2.3 is that in LayoutInflater the mConstructorArgs[0] = mContext is only set during running calls to

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.3_r1/android/view/LayoutInflater.java/#352

protected void setMenuBackground(){

    getLayoutInflater().setFactory( new Factory() {

        @Override
        public View onCreateView (final String name, final Context context, final AttributeSet attrs ) {

            if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {

                try { // Ask our inflater to create the view
                    final LayoutInflater f = getLayoutInflater();
                    final View[] view = new View[1]:
                    try {
                        view[0] = f.createView( name, null, attrs );
                    } catch (InflateException e) {
                        hackAndroid23(name, attrs, f, view);
                    }
                    // Kind of apply our own background
                    new Handler().post( new Runnable() {
                        public void run () {
                            view.setBackgroundResource( R.drawable.gray_gradient_background);
                        }
                    } );
                    return view;
                }
                catch ( InflateException e ) {
                }
                catch ( ClassNotFoundException e ) {
                }
            }
            return null;
        }
    });
}

static void hackAndroid23(final String name,
    final android.util.AttributeSet attrs, final LayoutInflater f,
    final TextView[] view) {
    // mConstructorArgs[0] is only non-null during a running call to inflate()
    // so we make a call to inflate() and inside that call our dully XmlPullParser get's called
    // and inside that it will work to call "f.createView( name, null, attrs );"!
    try {
        f.inflate(new XmlPullParser() {
            @Override
            public int next() throws XmlPullParserException, IOException {
                try {
                    view[0] = (TextView) f.createView( name, null, attrs );
                } catch (InflateException e) {
                } catch (ClassNotFoundException e) {
                }
                throw new XmlPullParserException("exit");
            }   
        }, null, false);
    } catch (InflateException e1) {
        // "exit" ignored
    }
}

I tested it to work on Android 2.3 and to still work on earlier versions. If anything breaks again in later Android versions you'll simply see the default menu-style instead

Combine or merge JSON on node.js without jQuery

You can do it inline, without changing any variables like this:

let obj1 = { name: 'John' };
let obj2 = { surname: 'Smith' };
let obj = Object.assign({}, obj1, obj2); // { name: 'John', surname: 'Smith' }

If WorkSheet("wsName") Exists

A version without error-handling:

Function sheetExists(sheetToFind As String) As Boolean
    sheetExists = False
    For Each sheet In Worksheets
        If sheetToFind = sheet.name Then
            sheetExists = True
            Exit Function
        End If
    Next sheet
End Function

Visual Studio Code - Convert spaces to tabs

Ctrl+Shift+P, then "Convert Indentation to Tabs"

Deep-Learning Nan loss reasons

There are lots of things I have seen make a model diverge.

  1. Too high of a learning rate. You can often tell if this is the case if the loss begins to increase and then diverges to infinity.

  2. I am not to familiar with the DNNClassifier but I am guessing it uses the categorical cross entropy cost function. This involves taking the log of the prediction which diverges as the prediction approaches zero. That is why people usually add a small epsilon value to the prediction to prevent this divergence. I am guessing the DNNClassifier probably does this or uses the tensorflow opp for it. Probably not the issue.

  3. Other numerical stability issues can exist such as division by zero where adding the epsilon can help. Another less obvious one if the square root who's derivative can diverge if not properly simplified when dealing with finite precision numbers. Yet again I doubt this is the issue in the case of the DNNClassifier.

  4. You may have an issue with the input data. Try calling assert not np.any(np.isnan(x)) on the input data to make sure you are not introducing the nan. Also make sure all of the target values are valid. Finally, make sure the data is properly normalized. You probably want to have the pixels in the range [-1, 1] and not [0, 255].

  5. The labels must be in the domain of the loss function, so if using a logarithmic-based loss function all labels must be non-negative (as noted by evan pu and the comments below).

What is the best Java library to use for HTTP POST, GET etc.?

Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.

Matplotlib color according to class labels

The accepted answer has it spot on, but if you might want to specify which class label should be assigned to a specific color or label you could do the following. I did a little label gymnastics with the colorbar, but making the plot itself reduces to a nice one-liner. This works great for plotting the results from classifications done with sklearn. Each label matches a (x,y) coordinate.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = [4,8,12,16,1,4,9,16]
y = [1,4,9,16,4,8,12,3]
label = [0,1,2,3,0,1,2,3]
colors = ['red','green','blue','purple']

fig = plt.figure(figsize=(8,8))
plt.scatter(x, y, c=label, cmap=matplotlib.colors.ListedColormap(colors))

cb = plt.colorbar()
loc = np.arange(0,max(label),max(label)/float(len(colors)))
cb.set_ticks(loc)
cb.set_ticklabels(colors)

Scatter plot color labels

Using a slightly modified version of this answer, one can generalise the above for N colors as follows:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

N = 23 # Number of labels

# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))
# define the data
x = np.random.rand(1000)
y = np.random.rand(1000)
tag = np.random.randint(0,N,1000) # Tag each point with a corresponding label    

# define the colormap
cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0,N,N+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x,y,c=tag,s=np.random.randint(100,500,N),cmap=cmap,     norm=norm)
# create the colorbar
cb = plt.colorbar(scat, spacing='proportional',ticks=bounds)
cb.set_label('Custom cbar')
ax.set_title('Discrete color mappings')
plt.show()

Which gives:

enter image description here

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

Is there a way to programmatically scroll a scroll view to a specific edit text?

I made a small utility method based on Answer from WarrenFaith, this code also takes in account if that view is already visible in the scrollview, no need for scroll.

public static void scrollToView(final ScrollView scrollView, final View view) {

    // View needs a focus
    view.requestFocus();

    // Determine if scroll needs to happen
    final Rect scrollBounds = new Rect();
    scrollView.getHitRect(scrollBounds);
    if (!view.getLocalVisibleRect(scrollBounds)) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                scrollView.smoothScrollTo(0, view.getBottom());
            }
        });
    } 
}

How to enable CORS in flask

Here is what worked for me when I deployed to Heroku.

http://flask-cors.readthedocs.org/en/latest/
Install flask-cors by running - pip install -U flask-cors

from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/")
@cross_origin()
def helloWorld():
  return "Hello, cross-origin-world!"

Uploading Images to Server android

use below code it helps you....

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 4;
        options.inPurgeable = true;
        Bitmap bm = BitmapFactory.decodeFile("your path of image",options);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bm.compress(Bitmap.CompressFormat.JPEG,40,baos); 


        // bitmap object

        byteImage_photo = baos.toByteArray();

                    //generate base64 string of image

                   String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

  //send this encoded string to server

Search for an item in a Lua list

function valid(data, array)
 local valid = {}
 for i = 1, #array do
  valid[array[i]] = true
 end
 if valid[data] then
  return false
 else
  return true
 end
end

Here's the function I use for checking if data is in an array.

Binding Combobox Using Dictionary as the Datasource

SortedDictionary<string, int> userCache = new SortedDictionary<string, int>
{
  {"a", 1},
  {"b", 2},
  {"c", 3}
};
comboBox1.DataSource = new BindingSource(userCache, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";

But why are you setting the ValueMember to "Value", shouldn't it be bound to "Key" (and DisplayMember to "Value" as well)?

spring data jpa @query and pageable

I had the same issue - without Pageable method works fine.
When added as method parameter - doesn't work.

After playing with DB console and native query support came up to decision that method works like it should. However, only for upper case letters.
Logic of my application was that all names of entity starts from upper case letters.

Playing a little bit with it. And discover that IgnoreCase at method name do the "magic" and here is working solution:

public interface EmployeeRepository 
                            extends PagingAndSortingRepository<Employee, Integer> {

    Page<Employee> findAllByNameIgnoreCaseStartsWith(String name, Pageable pageable);

}

Where entity looks like:

@Data
@Entity
@Table(name = "tblEmployees")
public class Employee {

    @Id
    @Column(name = "empID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotEmpty
    @Size(min = 2, max = 20)
    @Column(name = "empName", length = 25)
    private String name;

    @Column(name = "empActive")
    private Boolean active;

    @ManyToOne
    @JoinColumn(name = "emp_dpID")
    private Department department;
}

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

Splitting a dataframe string column into multiple different columns

Is this what you are trying to do?

# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)

#  Split into individual elements by the '.' character
#  Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )

#  We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )

#  Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
#  V1 V2  V3  V4
#1  F US CLE V13
#2  F US CA6 U13
#3  F US CA6 U13
#4  F US CA6 U13
#5  F US CA6 U13
#6  F US CA6 U13

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

Regular expression to match a line that doesn't contain a word

Aforementioned (?:(?!hede).)* is great because it can be anchored.

^(?:(?!hede).)*$               # A line without hede

foo(?:(?!hede).)*bar           # foo followed by bar, without hede between them

But the following would suffice in this case:

^(?!.*hede)                    # A line without hede

This simplification is ready to have "AND" clauses added:

^(?!.*hede)(?=.*foo)(?=.*bar)   # A line with foo and bar, but without hede
^(?!.*hede)(?=.*foo).*bar       # Same

How to retrieve a module's path?

import os
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)

Do conditional INSERT with SQL?

If you're looking to do an "upsert" one of the most efficient ways currently in SQL Server for single rows is this:

UPDATE myTable ...


IF @@ROWCOUNT=0
    INSERT INTO myTable ....

You can also use the MERGE syntax if you're doing this with sets of data rather than single rows.

If you want to INSERT and not UPDATE then you can just write your single INSERT statement and use WHERE NOT EXISTS (SELECT ...)

What does the Ellipsis object do?

__getitem__ minimal ... example in a custom class

When the magic syntax ... gets passed to [] in a custom class, __getitem__() receives a Ellipsis class object.

The class can then do whatever it wants with this Singleton object.

Example:

class C(object):
    def __getitem__(self, k):
        return k

# Single argument is passed directly.
assert C()[0] == 0

# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)

# Slice notation generates a slice object.
assert C()[1:2:3] == slice(1, 2, 3)

# Ellipsis notation generates the Ellipsis class object.
# Ellipsis is a singleton, so we can compare with `is`.
assert C()[...] is Ellipsis

# Everything mixed up.
assert C()[1, 2:3:4, ..., 6] == (1, slice(2,3,4), Ellipsis, 6)

The Python built-in list class chooses to give it the semantic of a range, and any sane usage of it should too of course.

Personally, I'd just stay away from it in my APIs, and create a separate, more explicit method instead.

Tested in Python 3.5.2 and 2.7.12.

Android Studio-No Module

I had a similar issue of my app module disappearing, this was after a large merge (from hell). I found app.iml was missing <component name="FacetManager"> when compared with other projects and before the merge. So I copy and pasted the below under the root <module > element.

Manually editing the .iml files maybe ill advised so proceed at your own risk.

File: project root folder > app > app.iml

Add the following...

  <component name="FacetManager">
    <facet type="android-gradle" name="Android-Gradle">
      <configuration>
        <option name="GRADLE_PROJECT_PATH" value=":app" />
      </configuration>
    </facet>
    <facet type="android" name="Android">
      <configuration>
        <option name="SELECTED_BUILD_VARIANT" value="debug" />
        <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
        <afterSyncTasks>
          <task>generateDebugSources</task>
        </afterSyncTasks>
        <option name="ALLOW_USER_CONFIGURATION" value="false" />
        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res;file://$MODULE_DIR$/src/debug/res" />
        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
      </configuration>
    </facet>
  </component>

When do you use the "this" keyword?

Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

Looks like you're trying to both inherit the groupId from the parent, and simultaneously specify the parent using an inherited groupId!

In the child pom, use something like this:

<modelVersion>4.0.0</modelVersion>

<parent>
  <groupId>org.felipe</groupId>
  <artifactId>tutorial_maven</artifactId>
  <version>1.0-SNAPSHOT</version>
  <relativePath>../pom.xml</relativePath>
</parent>

<artifactId>tutorial_maven_jar</artifactId>

Using properties like ${project.groupId} won't work there. If you specify the parent in this way, then you can inherit the groupId and version in the child pom. Hence, you only need to specify the artifactId in the child pom.

CSS - Expand float child DIV height to parent's height

I learned of this neat trick in an internship interview. The original question is how do you ensure the height of each top component in three columns have the same height that shows all the content available. Basically create a child component that is invisible that renders the maximum possible height.

<div class="parent">
    <div class="assert-height invisible">
        <!-- content -->
    </div>
    <div class="shown">
        <!-- content -->
    </div>
</div>

How do you use a variable in a regular expression?

For multiple replace without regular expressions I went with the following:

      let str = "I am a cat man. I like cats";
      let find = "cat";
      let replace = "dog";


      // Count how many occurrences there are of the string to find 
      // inside the str to be examined.
      let findCount = str.split(find).length - 1;

      let loopCount = 0;

      while (loopCount < findCount) 
      {
        str = str.replace(find, replace);
        loopCount = loopCount + 1;
      }  

      console.log(str);
      // I am a dog man. I like dogs

The important part of the solution was found here

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
{
   echo "You did not fill out the required fields.";
}

Refresh DataGridView when updating data source

This is copy my answer from THIS place.

Only need to fill datagrid again like this:

this.XXXTableAdapter.Fill(this.DataSet.XXX);

If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()

Git clone particular version of remote repository

Probably git reset solves your problem.

git reset --hard -#commit hash-

How to elegantly check if a number is within a range?

There are a lot of options:

int x = 30;
if (Enumerable.Range(1,100).Contains(x))
    //true

if (x >= 1 && x <= 100)
    //true

Also, check out this SO post for regex options.

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

Agree with David. To add on, it may not be the case that we want to groupBy all columns other than the column(s) in aggregate function i.e, if we want to remove duplicates purely based on a subset of columns and retain all columns in the original dataframe. So the better way to do this could be using dropDuplicates Dataframe api available in Spark 1.4.0

For reference, see: https://spark.apache.org/docs/1.4.0/api/scala/index.html#org.apache.spark.sql.DataFrame

Read the current full URL with React?

If you need the full path of your URL, you can use vanilla Javascript:

window.location.href

To get just the path (minus domain name), you can use:

window.location.pathname

_x000D_
_x000D_
console.log(window.location.pathname); //yields: "/js" (where snippets run)_x000D_
console.log(window.location.href);     //yields: "https://stacksnippets.net/js"
_x000D_
_x000D_
_x000D_

Source: Location pathname Property - W3Schools

If you are not already using "react-router" you can install it using:

yarn add react-router

then in a React.Component within a "Route", you can call:

this.props.location.pathname

This returns the path, not including the domain name.

Thanks @abdulla-zulqarnain!

How to replace item in array?

Answer from @gilly3 is great.

How to extend this for array of objects

I prefer the following way to update the new updated record into my array of records when I get data from the server. It keeps the order intact and quite straight forward one liner.

users = users.map(u => u.id !== editedUser.id ? u : editedUser);

_x000D_
_x000D_
var users = [_x000D_
{id: 1, firstname: 'John', lastname: 'Sena'},_x000D_
{id: 2, firstname: 'Serena', lastname: 'Wilham'},_x000D_
{id: 3, firstname: 'William', lastname: 'Cook'}_x000D_
];_x000D_
_x000D_
var editedUser = {id: 2, firstname: 'Big Serena', lastname: 'William'};_x000D_
_x000D_
users = users.map(u => u.id !== editedUser.id ? u : editedUser);_x000D_
_x000D_
console.log('users -> ', users);
_x000D_
_x000D_
_x000D_

Can Python test the membership of multiple values in a list?

Here's how I did it:

A = ['a','b','c']
B = ['c']
logic = [(x in B) for x in A]
if True in logic:
    do something

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

Is it .yaml or .yml?

The nature and even existence of file extensions is platform-dependent (some obscure platforms don't even have them, remember) -- in other systems they're only conventional (UNIX and its ilk), while in still others they have definite semantics and in some cases specific limits on length or character content (Windows, etc.).

Since the maintainers have asked that you use ".yaml", that's as close to an "official" ruling as you can get, but the habit of 8.3 is hard to get out of (and, appallingly, still occasionally relevant in 2013).

Equivalent of String.format in jQuery

The source code for ASP.NET AJAX is available for your reference, so you can pick through it and include the parts you want to continue using into a separate JS file. Or, you can port them to jQuery.

Here is the format function...

String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

And here are the endsWith and startsWith prototype functions...

String.prototype.endsWith = function (suffix) {
  return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
  return (this.substr(0, prefix.length) === prefix);
}

Sorting a tab delimited file

pipe it through something like awk '{ print print $1"\t"$2"\t"$3"\t"$4"\t"$5 }'. This will change the spaces to tabs.

SVG fill color transparency / alpha?

As a not yet fully standardized solution (though in alignment with the color syntax in CSS3) you can use e.g fill="rgba(124,240,10,0.5)". Works fine in Firefox, Opera, Chrome.

Here's an example.

How to tell if UIViewController's view is visible

you can check it by window property

if(viewController.view.window){

// view visible

}else{

// no visible

}

./configure : /bin/sh^M : bad interpreter

Your configure file contains CRLF line endings (windows style) instead of simple LF line endings (unix style). Did you transfer it using FTP mode ASCII from Windows?

You can use

dos2unix configure

to fix this, or open it in vi and use :%s/^M//g; to substitute them all (use CTRL+V, CTRL+M to get the ^M)

Python 3.1.1 string to hex

You've already got some good answers, but I thought you might be interested in a bit of the background too.

Firstly you're missing the quotes. It should be:

"hello".encode("hex")

Secondly this codec hasn't been ported to Python 3.1. See here. It seems that they haven't yet decided whether or not these codecs should be included in Python 3 or implemented in a different way.

If you look at the diff file attached to that bug you can see the proposed method of implementing it:

import binascii
output = binascii.b2a_hex(input)

Is it possible to print a variable's type in standard C++?

Very ugly but does the trick if you only want compile time info (e.g. for debugging):

auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;

Returns:

Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'

How to use Oracle's LISTAGG function with a unique filter?

I don't have an 11g instance available today but could you not use:

SELECT group_id,
       LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) AS names
  FROM (
       SELECT UNIQUE
              group_id,
              name
         FROM demotable
       )
 GROUP BY group_id

How to get param from url in angular 4?

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

BSTR to std::string (std::wstring) and vice versa

BSTR to std::wstring:

// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));

 
std::wstring to BSTR:

// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());

Doc refs:

  1. std::basic_string<typename CharT>::basic_string(const CharT*, size_type)
  2. std::basic_string<>::empty() const
  3. std::basic_string<>::data() const
  4. std::basic_string<>::size() const
  5. SysStringLen()
  6. SysAllocStringLen()

One time page refresh after first page load

<script>

function reloadIt() {
    if (window.location.href.substr(-2) !== "?r") {
        window.location = window.location.href + "?r";
    }
}

setTimeout('reloadIt()', 1000)();

</script>

this works perfectly

How to search a string in String array

Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:

bool has = arr.Contains(var); // .NET 3.5

or

bool has = Array.IndexOf(arr, var) >= 0;

For info: avoid names like var - this is a keyword in C# 3.0.

What's the best way to add a drop shadow to my UIView

The trick is defining the masksToBounds property of your view's layer properly:

view.layer.masksToBounds = NO;

and it should work.

(Source)

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

Initialize static variables in C++ class?

Some answers seem to be a little misleading.

You don't have to ...

  • Assign a value to some static object when initializing, because assigning a value is Optional.
  • Create another .cpp file for initializing since it can be done in the same Header file.

Also, you can even initialize a static object in the same class scope just like a normal variable using the inline keyword.


Initialize with no values in the same file

#include <string>
class A
{
    static std::string str;
    static int x;
};
std::string A::str;
int A::x;

Initialize with values in the same file

#include <string>
class A
{
    static std::string str;
    static int x;
};
std::string A::str = "SO!";
int A::x = 900;

Initialize in the same class scope using the inline keyword

#include <string>
class A
{
    static inline std::string str = "SO!";
    static inline int x = 900;
};

Aborting a shell script if any command returns a non-zero value

If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:

# Create the trap with   
#    trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah

Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.

Getting Access Denied when calling the PutObject operation with bucket-level permission

I encountered the same issue. My bucket was private and had KMS encryption. I was able to resolve this issue by putting in additional KMS permissions in the role. The following list is the bare minimum set of roles needed.

{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Sid": "AllowAttachmentBucketWrite",
        "Effect": "Allow",
        "Action": [
            "s3:PutObject",
            "kms:Decrypt",
            "s3:AbortMultipartUpload",
            "kms:Encrypt",
            "kms:GenerateDataKey"
        ],
        "Resource": [
            "arn:aws:s3:::bucket-name/*",
            "arn:aws:kms:kms-key-arn"
        ]
    }
  ]
}

Reference: https://aws.amazon.com/premiumsupport/knowledge-center/s3-large-file-encryption-kms-key/

Difference between HashMap and Map in Java..?

Map is an interface, i.e. an abstract "thing" that defines how something can be used. HashMap is an implementation of that interface.

How do I comment on the Windows command line?

Sometimes, it is convenient to add a comment to a command line. For that, you can use "&REM misc comment text" or, now that I know about it, "&:: misc comment text". For example:

REM SET Token="4C6F72656D20697073756D20646F6C6F" &REM This token is for localhost
SET Token="722073697420616D65742C20636F6E73" &REM This token is for production

This makes it easy to keep track of multiple sets of values when doing exploration, tests of concept, etc. This approach works because '&' introduces a new command on the same line.

In plain English, what does "git reset" do?

Please be aware, this is a simplified explanation intended as a first step in seeking to understand this complex functionality.

May be helpful for visual learners who want to visualise what their project state looks like after each of these commands:


For those who use Terminal with colour turned on (git config --global color.ui auto):

git reset --soft A and you will see B and C's stuff in green (staged and ready to commit)

git reset --mixed A (or git reset A) and you will see B and C's stuff in red (unstaged and ready to be staged (green) and then committed)

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)


Or for those who use a GUI program like 'Tower' or 'SourceTree'

git reset --soft A and you will see B and C's stuff in the 'staged files' area ready to commit

git reset --mixed A (or git reset A) and you will see B and C's stuff in the 'unstaged files' area ready to be moved to staged and then committed

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)

Python - How to convert JSON File to Dataframe

There are 2 inputs you might have and you can also convert between them.

  1. input: listOfDictionaries --> use @VikashSingh solution

example: [{"":{"...

The pd.DataFrame() needs a listOfDictionaries as input.

  1. input: jsonStr --> use @JustinMalinchak solution

example: '{"":{"...

If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:

jsonStr = json.dumps(listOfDictionaries)

Thus, switch back from jsonStr to listOfDictionaries first:

listOfDictionaries = json.loads(jsonStr)

Disable back button in android

Simply override the onBackPressed() method.

@Override
public void onBackPressed() { }

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

Shell - How to find directory of some command?

An alternative to type -a is command -V

Since most of the times I am interested in the first result only, I also pipe from head. This way the screen will not flood with code in case of a bash function.

command -V lshw | head -n1

What is the shortcut in IntelliJ IDEA to find method / functions?

Intellij v 13.1.4, OSX

The Open Symbol keyboard shortcut is command+shift+s

Avoid duplicates in INSERT INTO SELECT query in SQL Server

I was facing the same problem recently...
Heres what worked for me in MS SQL server 2017...
The primary key should be set on ID in table 2...
The columns and column properties should be the same of course between both tables. This will work the first time you run the below script. The duplicate ID in table 1, will not insert...

If you run it the second time, you will get a

Violation of PRIMARY KEY constraint error

This is the code:

Insert into Table_2
Select distinct *
from Table_1
where table_1.ID >1

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

Using Anaconda + Spyder (Python 3.7)

[code]

import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
print(soma)
sess = tf.compat.v1.Session()
with sess:
    print(sess.run(soma))

[console]

import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
Tensor("Const_8:0", shape=(), dtype=int32)
Out[18]: tensorflow.python.framework.ops.Tensor

print(soma)
Tensor("add_4:0", shape=(), dtype=int32)

sess = tf.compat.v1.Session()

with sess:
    print(sess.run(soma))
5

Inserting NOW() into Database with CodeIgniter's Active Record

run query to get now() from mysql i.e select now() as nowinmysql;

then use codeigniter to get this and put in

$data['created_on'] = $row->noinmyssql;
$this->db->insert($data);

How to generate gcc debug symbol outside the build target?

Check out the "--only-keep-debug" option of the strip command.

From the link:

The intention is that this option will be used in conjunction with --add-gnu-debuglink to create a two part executable. One a stripped binary which will occupy less space in RAM and in a distribution and the second a debugging information file which is only needed if debugging abilities are required.

OS detecting makefile

Another way to do this is by using a "configure" script. If you are already using one with your makefile, you can use a combination of uname and sed to get things to work out. First, in your script, do:

UNAME=uname

Then, in order to put this in your Makefile, start out with Makefile.in which should have something like

UNAME=@@UNAME@@

in it.

Use the following sed command in your configure script after the UNAME=uname bit.

sed -e "s|@@UNAME@@|$UNAME|" < Makefile.in > Makefile

Now your makefile should have UNAME defined as desired. If/elif/else statements are all that's left!

Convert JSON String To C# Object

add this ddl to reference to your project: System.Web.Extensions.dll

use this namespace: using System.Web.Script.Serialization;

public class IdName
{
    public int Id { get; set; }
    public string Name { get; set; }
}


   string jsonStringSingle = "{'Id': 1, 'Name':'Thulasi Ram.S'}".Replace("'", "\"");
   var entity = new JavaScriptSerializer().Deserialize<IdName>(jsonStringSingle);

   string jsonStringCollection = "[{'Id': 2, 'Name':'Thulasi Ram.S'},{'Id': 2, 'Name':'Raja Ram.S'},{'Id': 3, 'Name':'Ram.S'}]".Replace("'", "\"");
   var collection = new JavaScriptSerializer().Deserialize<IEnumerable<IdName>>(jsonStringCollection);

How to find if a native DLL file is compiled as x64 or x86?

There is an easy way to do this with CorFlags. Open the Visual Studio Command Prompt and type "corflags [your assembly]". You'll get something like this:

c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC>corflags "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll"

Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved.

Version : v2.0.50727 CLR Header: 2.5 PE : PE32 CorFlags : 24 ILONLY : 0 32BIT : 0 Signed : 1

You're looking at PE and 32BIT specifically.

  • Any CPU:

    PE: PE32
    32BIT: 0

  • x86:

    PE: PE32
    32BIT: 1

  • x64:

    PE: PE32+
    32BIT: 0

Pandas: ValueError: cannot convert float NaN to integer

if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int) if you want your dataset to be unchangeable.

Typescript interface default values

Can I tell the interface to default the properties I don't supply to null? What would let me do this

No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support

Alternative

But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:

interface IX {
  a: string,
  b?: any,
  c?: AnotherType
}

And now when you create it you only need to provide a:

let x: IX = {
    a: 'abc'
};

You can provide the values as needed:

x.a = 'xyz'
x.b = 123
x.c = new AnotherType()

How do I import a .sql file in mysql database using PHP?

I have Test your code, this error shows when you already have the DB imported or with some tables with the same name, also the Array error that shows is because you add in in the exec parenthesis, here is the fixed version:

<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
$output=array();
exec($command,$output,$worked);
switch($worked){
    case 0:
        echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
        break;
    case 1:
        echo 'There was an error during import.';
        break;
}
?> 

How do I copy a folder from remote to local using scp?

Typical scenario,

scp -r -P port username@ip:/path-to-folder  .

explained with an sample,

scp -r -P 27000 [email protected]:/tmp/hotel_dump .

where,

port = 27000
username = "abc" , remote server username
path-to-folder = tmp/hotel_dump
. = current local directory

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

If embed no longer works for you, try with /v instead:

<iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>

Find value in an array

If you want find one value from array, use Array#find:

arr = [1,2,6,4,9] 
arr.find {|e| e % 3 == 0}   #=>  6

See also:

arr.select {|e| e % 3 == 0} #=> [ 6, 9 ]
e.include? 6              #=> true

To find if a value exists in an Array you can also use #in? when using ActiveSupport. #in? works for any object that responds to #include?:

arr = [1, 6]
6.in? arr                 #=> true

z-index issue with twitter bootstrap dropdown menu

I had the same problem and after reading this topic, I've solved adding this to my CSS:

.navbar-fixed-top {
    z-index: 10000;
}

because in my case, I'm using the fixed top menu.

Foreign key referencing a 2 columns primary key in SQL Server

Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:

ALTER TABLE dbo.Content
   ADD CONSTRAINT FK_Content_Libraries
   FOREIGN KEY(LibraryID, Application)
   REFERENCES dbo.Libraries(ID, Application)

Is that what you're using?? If (ID, Application) is indeed the primary key on dbo.Libraries, this statement should definitely work.

Luk: just to check - can you run this statement in your database and report back what the output is??

SELECT
    tc.TABLE_NAME,
    tc.CONSTRAINT_NAME, 
    ccu.COLUMN_NAME
FROM 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
INNER JOIN 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu 
      ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE
    tc.TABLE_NAME IN ('Libraries', 'Content')

How to vertically align an image inside a div

You could do this:

Demo

http://jsfiddle.net/DZ8vW/1

CSS

.frame {
    height: 25px;      /* Equals maximum image height */
    line-height: 25px;
    width: 160px;
    border: 1px solid red;
    
    text-align: center; 
    margin: 1em 0;
    position: relative; /* Changes here... */
}
img {
    background: #3A6F9A;
    max-height: 25px;
    max-width: 160px;
    top: 50%;           /* Here.. */
    left: 50%;          /* Here... */
    position: absolute; /* And here */
}    

JavaScript

$("img").each(function(){
    this.style.marginTop = $(this).height() / -2 + "px";
})

jQuery: get parent, parent id?

 $(this).closest('ul').attr('id');

How to select true/false based on column value?

Use a CASE. I would post the specific code, but need more information than is supplied in the post - such as the data type of EntityProfile and what is usually stored in it. Something like:

CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END

Edit - the entire SELECT statement, as per the info in the comments:

SELECT EntityID, EntityName, 
       CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END AS HasProfile
FROM Entity

No LEFT JOIN necessary in this case...

Looping through GridView rows and Checking Checkbox Control

you have to iterate gridview Rows

for (int count = 0; count < grd.Rows.Count; count++)
{
    if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
    {     
      ((Label)grd.Rows[count].FindControl("labelID")).Text
    }
}

ViewDidAppear is not called when opening app from background

Curious about the exact sequence of events, I instrumented an app as follows: (@Zohaib, you can use the NSNotificationCenter code below to answer your question).

// AppDelegate.m

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    NSLog(@"app will enter foreground");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSLog(@"app did become active");
}

// ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"view did load");

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)appDidBecomeActive:(NSNotification *)notification {
    NSLog(@"did become active notification");
}

- (void)appWillEnterForeground:(NSNotification *)notification {
    NSLog(@"will enter foreground notification");
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"view will appear");
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"view did appear");
}

At launch, the output looks like this:

2013-04-07 09:31:06.505 myapp[15459:11303] view did load
2013-04-07 09:31:06.507 myapp[15459:11303] view will appear
2013-04-07 09:31:06.511 myapp[15459:11303] app did become active
2013-04-07 09:31:06.512 myapp[15459:11303] did become active notification
2013-04-07 09:31:06.517 myapp[15459:11303] view did appear

Enter the background then reenter the foreground:

2013-04-07 09:32:05.923 myapp[15459:11303] app will enter foreground
2013-04-07 09:32:05.924 myapp[15459:11303] will enter foreground notification
2013-04-07 09:32:05.925 myapp[15459:11303] app did become active
2013-04-07 09:32:05.926 myapp[15459:11303] did become active notification

Why is semicolon allowed in this python snippet?

I realize I am biased as an old C programmer, but there are times when the various Python conventions make things hard to follow. I find the indent convention a bit of an annoyance at times.

Sometimes, clarity of when a statement or block ends is very useful. Standard C code will often read something like this:

for(i=0; i<100; i++) {
    do something here;
    do another thing here;
}

continue doing things;

where you use the whitespace for a lot of clarity - and it is easy to see where the loop ends.

Python does let you terminate with an (optional) semicolon. As noted above, that does NOT mean that there is a statement to execute followed by a 'null' statement. SO, for example,

print(x);
print(y);

Is the same as

print(x)
print(y)

If you believe that the first one has a null statement at the end of each line, try - as suggested - doing this:

print(x);;

It will throw a syntax error.

Personally, I find the semicolon to make code more readable when you have lots of nesting and functions with many arguments and/or long-named args. So, to my eye, this is a lot clearer than other choices:

if some_boolean_is_true:
    call_function(
        long_named_arg_1,
        long_named_arg_2,
        long_named_arg_3,
        long_named_arg_4
    );

since, to me, it lets you know that last ')' ends some 'block' that ran over many lines.

I personally think there is much to much made of PEP style guidelines, IDEs that enforce them, and the belief there is 'only one Pythonic way to do things'. If you believe the latter, go look at how to format numbers: as of now, Python supports four different ways to do it.

I am sure I will be flamed by some diehards, but the compiler/interpreter doesn't care if the arguments have long or short names, and - but for the indentation convention in Python - doesn't care about whitespace. The biggest problem with code is giving clarity to another human (and even yourself after months of work) to understand what is going on, where things start and end, etc.

How to install Selenium WebDriver on Mac OS

First up you need to download Selenium jar files from http://www.seleniumhq.org/download/. Then you'd need an IDE, something like IntelliJ or Eclipse. Then you'll have to map your jar files to those IDEs. Then depending on which language/framework you choose, you'll have to download the relevant library files, for example, if you're using JUnit you'll have to download Junit 4.11 jar file. Finally don't forget to download the drivers for Chrome and Safari (firefox driver comes standard with selenium). Once done, you can start coding and testing your code with the browser of your choice.

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

Python POST binary data

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

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

How to hide a status bar in iOS?

add this key key from dropdownlist in "info.plist" and voila you will no more see top bar that includes elements something like GSM,wifi icon etc.
enter image description here