Programs & Examples On #Aspxgridview

ASPxGridView is usually in reference to the ASPxGridView provided by DevExpress. It's one of the prime products offered by DevExpress Inc. in support of ASP.Net WebForms.

set column width of a gridview in asp.net

<asp:GridView ID="GridView1" runat="server">
    <HeaderStyle Width="10%" />
    <RowStyle Width="10%" />
    <FooterStyle Width="10%" />
    <Columns>
        <asp:BoundField HeaderText="Name" DataField="LastName" 
            HeaderStyle-Width="10%" ItemStyle-Width="10%"
            FooterStyle-Width="10%" />
    </Columns>
</asp:GridView>

Fetch: POST json data

It might be useful to somebody:

I was having the issue that formdata was not being sent for my request

In my case it was a combination of following headers that were also causing the issue and the wrong Content-Type.

So I was sending these two headers with the request and it wasn't sending the formdata when I removed the headers that worked.

"X-Prototype-Version" : "1.6.1",
"X-Requested-With" : "XMLHttpRequest"

Also as other answers suggest that the Content-Type header needs to be correct.

For my request the correct Content-Type header was:

"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"

So bottom line if your formdata is not being attached to the Request then it could potentially be your headers. Try bringing your headers to a minimum and then try adding them one by one to see if your problem is rsolved.

Reading an Excel file in python using pandas

Thought i should add here, that if you want to access rows or columns to loop through them, you do this:

import pandas as pd

# open the file
xlsx = pd.ExcelFile("PATH\FileName.xlsx")

# get the first sheet as an object
sheet1 = xlsx.parse(0)
    
# get the first column as a list you can loop through
# where the is 0 in the code below change to the row or column number you want    
column = sheet1.icol(0).real

# get the first row as a list you can loop through
row = sheet1.irow(0).real

Edit:

The methods icol(i) and irow(i) are deprecated now. You can use sheet1.iloc[:,i] to get the i-th col and sheet1.iloc[i,:] to get the i-th row.

A variable modified inside a while loop is not remembered

Though this is an old question and asked several times, here's what I'm doing after hours fidgeting with here strings, and the only option that worked for me is to store the value in a file during while loop sub-shells and then retrieve it. Simple.

Use echo statement to store and cat statement to retrieve. And the bash user must chown the directory or have read-write chmod access.

#write to file
echo "1" > foo.txt

while condition; do 
    if (condition); then
        #write again to file
        echo "2" > foo.txt      
    fi
done

#read from file
echo "Value of \$foo in while loop body: $(cat foo.txt)"

How to return a result (startActivityForResult) from a TabHost Activity?

Intent.FLAG_ACTIVITY_FORWARD_RESULT?

If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity.

Page redirect with successful Ajax request

$.ajax({
        url: 'mail3.php',
        type: 'POST',
        data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,

        success: function(result) {

            //console.log(result);
            $('#results,#errors').remove();
            $('#contactWrapper').append('<p id="results">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();

            });

            if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"

        }
    });

How can I add an item to a ListBox in C# and WinForms?

list.Items.add(new ListBoxItem("name", "value"));

The internal (default) data structure of the ListBox is the ListBoxItem.

Python function pointer

funcdict = {
  'mypackage.mymodule.myfunction': mypackage.mymodule.myfunction,
    ....
}

funcdict[myvar](parameter1, parameter2)

iOS for VirtualBox

You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.

Maven parent pom vs modules pom

  1. An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.

  2. If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.

  3. A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to be shared by all, but avoids the problem described in #2.

  4. The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.

  5. Apache CXF is an example the pattern in #2.

How to get the date and time values in a C program?

One liner to get local time information: struct tm *tinfo = localtime(&(time_t){time(NULL)});

C++ compiling on Windows and Linux: ifdef switch

It depends on the compiler. If you compile with, say, G++ on Linux and VC++ on Windows, this will do :

#ifdef linux
    ...
#elif _WIN32
    ...
#else
    ...
#endif

How should we manage jdk8 stream for null values

Stuart's answer provides a great explanation, but I'd like to provide another example.

I ran into this issue when attempting to perform a reduce on a Stream containing null values (actually it was LongStream.average(), which is a type of reduction). Since average() returns OptionalDouble, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.

So, as the OP suggests, I added a filter like so:

list.stream()
    .filter(o -> o != null)
    .reduce(..);

Or as tangens pointed out below, use the predicate provided by the Java API:

list.stream()
    .filter(Objects::nonNull)
    .reduce(..);

From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.

See this explanation from Mike Williams' Google Maps API v2 tutorial:

If you try to use style="width:100%;height:100%" on your map div, you get a map div that has zero height. That's because the div tries to be a percentage of the size of the <body>, but by default the <body> has an indeterminate height.

There are ways to determine the height of the screen and use that number of pixels as the height of the map div, but a simple alternative is to change the <body> so that its height is 100% of the page. We can do this by applying style="height:100%" to both the <body> and the <html>. (We have to do it to both, otherwise the <body> tries to be 100% of the height of the document, and the default for that is an indeterminate height.)

Add the 100% size to html and body in your css

    html, body, #map-canvas {
        margin: 0;
        padding: 0;
        height: 100%;
        width: 100%;
    }

Add it inline to any divs that don't have an id:

<body>
  <div style="height:100%; width: 100%;"> 
    <div id="map-canvas"></div>
  </div>
</body>

Include jQuery in the JavaScript Console

Per this answer:

fetch('https://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => eval(r))

For some reason I have to execute it twice to get the new '$' (which I have to do with the other methods as well), but it works.

This is the equivalent if your browser isn't so modern:

fetch('http://code.jquery.com/jquery-latest.min.js').then(function(r){return r.text()}).then(function(r){eval(r)})

Passing parameters to addTarget:action:forControlEvents

action:@selector(switchToNewsDetails:)

You do not pass parameters to switchToNewsDetails: method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:

  1. with no parameters

    action:@selector(switchToNewsDetails)
    
  2. with 1 parameter indicating the control that sends the message

    action:@selector(switchToNewsDetails:)
    
  3. With 2 parameters indicating the control that sends the message and the event that triggered the message:

    action:@selector(switchToNewsDetails:event:)
    

It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:

  1. set a tag property to each button equal to required index
  2. in switchToNewsDetails: method you can obtain that index and open appropriate deatails:

    - (void)switchToNewsDetails:(UIButton*)sender{
        [self openDetails:sender.tag];
        // Or place opening logic right here
    }
    

joining two select statements

Not sure what you are trying to do, but you have two select clauses. Do this instead:

SELECT * 
FROM ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
       WHERE products_id = 181) AS A
JOIN ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id
       WHERE products_id = 180) AS B

ON A.orders_id=B.orders_id

Update:

You could probably reduce it to something like this:

SELECT o.orders_id, 
       op1.products_id, 
       op1.quantity, 
       op2.products_id, 
       op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id  
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id  
WHERE op1.products_id = 180
AND op2.products_id = 181

How do you replace all the occurrences of a certain character in a string?

You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:

>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'

This would of course fail if there is multiple numbers in the input. a quick check would be:

assert(age in input_given)

and also:

assert(len(name)<len(input_given))

How to get number of entries in a Lua table?

You could use penlight library. This has a function size which gives the actual size of the table.

It has implemented many of the function that we may need while programming and missing in Lua.

Here is the sample for using it.

> tablex = require "pl.tablex"
> a = {}
> a[2] = 2
> a[3] = 3 
> a['blah'] = 24

> #a
0

> tablex.size(a)
3

Why is MySQL InnoDB insert so slow?

Solution

  1. Create new UNIQUE key that is identical to your current PRIMARY key
  2. Add new column id is unsigned integer, auto_increment
  3. Create primary key on new id column

Bam, immediate 10x+ insert improvement.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

this works for me:

It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.

Rock, Paper, Scissors Game Java

int w =0 , l =0, d=0, i=0;
    Scanner sc = new Scanner(System.in);

// try tentimes
    while (i<10) {


        System.out.println("scissor(1) ,Rock(2),Paper(3) ");
        int n = sc.nextInt();
        int m =(int)(Math.random()*3+1);


        if(n==m){

            System.out.println("Com:"+m +"so>>> " + "draw");
            d++;


        }else if ((n-1)%3==(m%3)){
            w++;
            System.out.println("Com:"+m +"so>>> " +"win");
        }
        else if(n >=4 )
        {
            System.out.println("pleas enter correct number)");


    }
        else {
            System.out.println("Com:"+m +"so>>> " +"lose");
            l++;

        }
        i++;

UIScrollView scroll to bottom programmatically

Using UIScrollView's setContentOffset:animated: function to scroll to the bottom in Swift.

let bottomOffset : CGPoint = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)

How to insert data using wpdb

global $wpdb;
$insert = $wpdb->query("INSERT INTO `front-post`(`id`, `content`) VALUES ('$id', '$content')");

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

What does "int 0x80" mean in assembly code?

As mentioned, it causes control to jump to interrupt vector 0x80. In practice what this means (at least under Linux) is that a system call is invoked; the exact system call and arguments are defined by the contents of the registers. For example, exit() can be invoked by setting %eax to 1 followed by 'int 0x80'.

How to get the ActionBar height?

A ready method to fulfill the most popular answer:

public static int getActionBarHeight(
  Activity activity) {

  int actionBarHeight = 0;
  TypedValue typedValue = new TypedValue();

  try {

    if (activity
      .getTheme()
      .resolveAttribute(
        android.R.attr.actionBarSize,
        typedValue,
        true)) {

      actionBarHeight =
        TypedValue.complexToDimensionPixelSize(
          typedValue.data,
          activity
            .getResources()
            .getDisplayMetrics());
    }

  } catch (Exception ignore) {
  }

  return actionBarHeight;
}

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

How to find out which JavaScript events fired?

Looks like Firebug (Firefox add-on) has the answer:

  • open Firebug
  • right click the element in HTML tab
  • click Log Events
  • enable Console tab
  • click Persist in Console tab (otherwise Console tab will clear after the page is reloaded)
  • select Closed (manually)
  • there will be something like this in Console tab:

    ...
    mousemove clientX=1097, clientY=292
    popupshowing
    mousedown clientX=1097, clientY=292
    focus
    mouseup clientX=1097, clientY=292
    click clientX=1097, clientY=292
    mousemove clientX=1096, clientY=293
    ...
    

Source: Firebug Tip: Log Events

numpy: most efficient frequency counts for unique values in an array

Using pandas module:

>>> import pandas as pd
>>> import numpy as np
>>> x = np.array([1,1,1,2,2,2,5,25,1,1])
>>> pd.value_counts(x)
1     5
2     3
25    1
5     1
dtype: int64

How to order events bound with jQuery

I had been trying for ages to generalize this kind of process, but in my case I was only concerned with the order of first event listener in the chain.

If it's of any use, here is my jQuery plugin that binds an event listener that is always triggered before any others:

** UPDATED inline with jQuery changes (thanks Toskan) **

(function($) {
    $.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {
        var indexOfDot = eventType.indexOf(".");
        var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : "";

        eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
        handler = handler == undefined ? eventData : handler;
        eventData = typeof eventData == "function" ? {} : eventData;

        return this.each(function() {
            var $this = $(this);
            var currentAttrListener = this["on" + eventType];

            if (currentAttrListener) {
                $this.bind(eventType, function(e) {
                    return currentAttrListener(e.originalEvent); 
                });

                this["on" + eventType] = null;
            }

            $this.bind(eventType + eventNameSpace, eventData, handler);

            var allEvents = $this.data("events") || $._data($this[0], "events");
            var typeEvents = allEvents[eventType];
            var newEvent = typeEvents.pop();
            typeEvents.unshift(newEvent);
        });
    };
})(jQuery);

Things to note:

  • This hasn't been fully tested.
  • It relies on the internals of the jQuery framework not changing (only tested with 1.5.2).
  • It will not necessarily get triggered before event listeners that are bound in any way other than as an attribute of the source element or using jQuery bind() and other associated functions.

Table scroll with HTML and CSS

_x000D_
_x000D_
  .outer {_x000D_
    overflow-y: auto;_x000D_
    height: 300px;_x000D_
  }_x000D_
_x000D_
  .outer {_x000D_
    width: 100%;_x000D_
    -layout: fixed;_x000D_
  }_x000D_
_x000D_
  .outer th {_x000D_
    text-align: left;_x000D_
    top: 0;_x000D_
    position: sticky;_x000D_
    background-color: white;_x000D_
  }
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
    <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
    <title>MYCRUD</title>_x000D_
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container-fluid col-md-11">_x000D_
  <div class="row">_x000D_
_x000D_
    <div class="col-lg-12">_x000D_
_x000D_
   _x000D_
        <div class="card-body">_x000D_
          <div class="outer">_x000D_
_x000D_
            <table class="table table-hover bg-light">_x000D_
              <thead>_x000D_
                <tr>_x000D_
                  <th scope="col">ID</th>_x000D_
                  <th scope="col">Marca</th>_x000D_
                  <th scope="col">Editar</th>_x000D_
                  <th scope="col">Eliminar</th>_x000D_
                </tr>_x000D_
              </thead>_x000D_
              <tbody>_x000D_
_x000D_
                _x000D_
                  <tr>_x000D_
                    <td>4</td>_x000D_
                    <td>Toyota</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>3</td>_x000D_
                    <td>Honda </td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>5</td>_x000D_
                    <td>Myo</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>6</td>_x000D_
                    <td>Acer</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>7</td>_x000D_
                    <td>HP</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>8</td>_x000D_
                    <td>DELL</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                                  <tr>_x000D_
                    <td>9</td>_x000D_
                    <td>LOGITECH</td>_x000D_
                    <td> <a class="btn btn-success" href="#">_x000D_
                        <i class="fa fa-edit"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                    <td> <a class="btn btn-danger" href="#">_x000D_
                        <i class="fa fa-trash"></i>_x000D_
                      </a>_x000D_
                    </td>_x000D_
                  </tr>_x000D_
_x000D_
                              </tbody>_x000D_
            </table>_x000D_
          </div>_x000D_
_x000D_
        </div>_x000D_
_x000D_
     _x000D_
_x000D_
_x000D_
_x000D_
_x000D_
    </div>_x000D_
_x000D_
  </div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Producing a new line in XSLT

I second Nic Gibson's method, this was always my favorite:

<xsl:variable name='nl'><xsl:text>
</xsl:text></xsl:variable>

However I have been using the Ant task <echoxml> to create stylesheets and run them against files. The task will do attribute value templates, e.g. ${DSTAMP} , but is also will reformat your xml, so in some cases, the entity reference is preferable.

<xsl:variable name='nl'><xsl:text>&#xa;</xsl:text></xsl:variable>

How do I get a reference to the app delegate in Swift?

In Swift 3.0 you can get the appdelegate reference by

let appDelegate = UIApplication.shared.delegate as! AppDelegate

In SQL, is UPDATE always faster than DELETE+INSERT?

The question of speed is irrelevant without a specific speed problem.

If you are writing SQL code to make a change to an existing row, you UPDATE it. Anything else is incorrect.

If you're going to break the rules of how code should work, then you'd better have a damn good, quantified reason for it, and not a vague idea of "This way is faster", when you don't have any idea what "faster" is.

Mockito: Trying to spy on method is calling the original method

One more possible scenario which may causing issues with spies is when you're testing spring beans (with spring test framework) or some other framework that is proxing your objects during test.

Example

@Autowired
private MonitoringDocumentsRepository repository

void test(){
    repository = Mockito.spy(repository)
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

In above code both Spring and Mockito will try to proxy your MonitoringDocumentsRepository object, but Spring will be first, which will cause real call of findMonitoringDocuments method. If we debug our code just after putting a spy on repository object it will look like this inside debugger:

repository = MonitoringDocumentsRepository$$EnhancerBySpringCGLIB$$MockitoMock$

@SpyBean to the rescue

If instead @Autowired annotation we use @SpyBean annotation, we will solve above problem, the SpyBean annotation will also inject repository object but it will be firstly proxied by Mockito and will look like this inside debugger

repository = MonitoringDocumentsRepository$$MockitoMock$$EnhancerBySpringCGLIB$

and here is the code:

@SpyBean
private MonitoringDocumentsRepository repository

void test(){
    Mockito.doReturn(docs1, docs2)
            .when(repository).findMonitoringDocuments(Mockito.nullable(MonitoringDocumentSearchRequest.class));
}

Can I change the height of an image in CSS :before/:after pseudo-elements?

diplay: block; have no any effect

positionin also works very strange accodringly to frontend foundamentals, so be careful

body:before{ 
    content:url(https://i.imgur.com/LJvMTyw.png);
    transform: scale(.3);
    position: fixed;
    left: 50%;
    top: -6%;
    background: white;
}

Java Class that implements Map and keeps insertion order?

If an immutable map fits your needs then there is a library by google called guava (see also guava questions)

Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.

ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.

inherit from two classes in C#

Make two interfaces IA and IB:

public interface IA
{
    public void methodA(int value);
}

public interface IB
{
    public void methodB(int value);
}

Next make A implement IA and B implement IB.

public class A : IA
{
    public int fooA { get; set; }
    public void methodA(int value) { fooA = value; }
}

public class B : IB
{
    public int fooB { get; set; }
    public void methodB(int value) { fooB = value; }
}

Then implement your C class as follows:

public class C : IA, IB
{
    private A _a;
    private B _b;

    public C(A _a, B _b)
    {
        this._a = _a;
        this._b = _b;
    }

    public void methodA(int value) { _a.methodA(value); }
    public void methodB(int value) { _b.methodB(value); }
}

Generally this is a poor design overall because you can have both A and B implement a method with the same name and variable types such as foo(int bar) and you will need to decide how to implement it, or if you just call foo(bar) on both _a and _b. As suggested elsewhere you should consider a .A and .B properties instead of combining the two classes.

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

Web Application context extended Application Context which is designed to work with the standard javax.servlet.ServletContext so it's able to communicate with the container.

public interface WebApplicationContext extends ApplicationContext {
    ServletContext getServletContext();
}

Beans, instantiated in WebApplicationContext will also be able to use ServletContext if they implement ServletContextAware interface

package org.springframework.web.context;
public interface ServletContextAware extends Aware { 
     void setServletContext(ServletContext servletContext);
}

There are many things possible to do with the ServletContext instance, for example accessing WEB-INF resources(xml configs and etc.) by calling the getResourceAsStream() method. Typically all application contexts defined in web.xml in a servlet Spring application are Web Application contexts, this goes both to the root webapp context and the servlet's app context.

Also, depending on web application context capabilities may make your application a little harder to test, and you may need to use MockServletContext class for testing.

Difference between servlet and root context Spring allows you to build multilevel application context hierarchies, so the required bean will be fetched from the parent context if it's not present in the current application context. In web apps as default there are two hierarchy levels, root and servlet contexts: Servlet and root context.

This allows you to run some services as the singletons for the entire application (Spring Security beans and basic database access services typically reside here) and another as separated services in the corresponding servlets to avoid name clashes between beans. For example one servlet context will be serving the web pages and another will be implementing a stateless web service.

This two level separation comes out of the box when you use the spring servlet classes: to configure the root application context you should use context-param tag in your web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/root-context.xml
            /WEB-INF/applicationContext-security.xml
    </param-value>
</context-param>

(the root application context is created by ContextLoaderListener which is declared in web.xml

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 

) and servlet tag for the servlet application contexts

<servlet>
   <servlet-name>myservlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>app-servlet.xml</param-value>
   </init-param>
</servlet>

Please note that if init-param will be omitted, then spring will use myservlet-servlet.xml in this example.

See also: Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

Get a filtered list of files in a directory

You can use pathlib that is available in Python standard library 3.4 and above.

from pathlib import Path

files = [f for f in Path.cwd().iterdir() if f.match("145592*.jpg")]

Keep only date part when using pandas.to_datetime

This is a simple way to extract the date:

import pandas as pd

d='2015-01-08 22:44:09' 
date=pd.to_datetime(d).date()
print(date)

What is the difference between statically typed and dynamically typed languages?

Static Typing: The languages such as Java and Scala are static typed.

The variables have to be defined and initialized before they are used in a code.

for ex. int x; x = 10;

System.out.println(x);

Dynamic Typing: Perl is an dynamic typed language.

Variables need not be initialized before they are used in code.

y=10; use this variable in the later part of code

Convert binary to ASCII and vice versa

For ASCII characters in the range [ -~] on Python 2:

>>> import binascii
>>> bin(int(binascii.hexlify('hello'), 16))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> binascii.unhexlify('%x' % n)
'hello'

In Python 3.2+:

>>> bin(int.from_bytes('hello'.encode(), 'big'))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
'hello'

To support all Unicode characters in Python 3:

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0'

Here's single-source Python 2/3 compatible version:

import binascii

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return int2bytes(n).decode(encoding, errors)

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

Example

>>> text_to_bits('hello')
'0110100001100101011011000110110001101111'
>>> text_from_bits('110100001100101011011000110110001101111') == u'hello'
True

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

How to convert column with string type to int form in pyspark data frame?

Another way to do it is using the StructField if you have multiple fields that needs to be modified.

Ex:

from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
       StructField('OPEN_FLG',IntegerType(),True),
       StructField('I1_GNDR_CODE',StringType(),True),
       StructField('TRW_INCOME_CD_V4',StringType(),True),
       StructField('ASIAN_CD',IntegerType(),True),
       StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
       ]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)

Output:

Before

root
 |-- CLICK_FLG: string (nullable = true)
 |-- OPEN_FLG: string (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)

After:

root
 |-- CLICK_FLG: integer (nullable = true)
 |-- OPEN_FLG: integer (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)

This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.

It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.

Setting href attribute at runtime

<style>
a:hover {
    cursor:pointer;
}
</style>

<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(".link").click(function(){
        var href = $(this).attr("href").split("#");
        $(".results").text(href[1]);
    })
})
</script>



<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>


<br /><br />
<div class="results"></div>

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

Make flex items take content width, not width of parent container

Use align-items: flex-start on the container, or align-self: flex-start on the flex items.

No need for display: inline-flex.


An initial setting of a flex container is align-items: stretch. This means that flex items will expand to cover the full length of the container along the cross axis.

The align-self property does the same thing as align-items, except that align-self applies to flex items while align-items applies to the flex container.

By default, align-self inherits the value of align-items.

Since your container is flex-direction: column, the cross axis is horizontal, and align-items: stretch is expanding the child element's width as much as it can.

You can override the default with align-items: flex-start on the container (which is inherited by all flex items) or align-self: flex-start on the item (which is confined to the single item).


Learn more about flex alignment along the cross axis here:

Learn more about flex alignment along the main axis here:

Is there a Java API that can create rich Word documents?

In 2007 my project successfully used OpenOffice.org's Universal Network Objects (UNO) interface to programmatically generate MS-Word compatible documents (*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework).

OpenOffice UNO also lets you build MS-Office-compatible charts, spreadsheets, presentations, etc. We were able to dynamically build sophisticated Word documents, including charts and tables.

We simplified the process by using template MS-Word documents with bookmark inserts into which the software inserted content, however, you can build documents completely from scratch. The goal was to have the software generate report documents that could be shared and further tweaked by end-users before converting them to PDF for final delivery and archival.

You can optionally produce documents in OpenOffice formats if you want users to use OpenOffice instead of MS-Office. In our case the users want to use MS-Office tools.

UNO is included within the OpenOffice suite. We simply linked our Java app to UNO-related libraries within the suite. An OpenOffice Software Development Kit (SDK) is available containing example applications and the UNO Developer's Guide.

I have not investigated whether the latest OpenOffice UNO can generate MS-Office 2007 Open XML document formats.

The important things about OpenOffice UNO are:

  1. It is freeware
  2. It supports multiple languages (e.g. Visual Basic, Java, C++, and others).
  3. It is platform-independent (Windows, Linux, Unix, etc.).

Here are some useful web sites:

mysql query result in php variable

$query    =    "SELECT username, userid FROM user WHERE username = 'admin' ";
$result    =    $conn->query($query);

if (!$result) {
  echo 'Could not run query: ' . mysql_error();
  exit;
}

$arrayResult    =    mysql_fetch_array($result);

//Now you can access $arrayResult like this

$arrayResult['userid'];    // output will be userid which will be in database
$arrayResult['username'];  // output will be admin

//Note- userid and username will be column name of user table.

What's the difference between JPA and Hibernate?

As you state JPA is just a specification, meaning there is no implementation. You can annotate your classes as much as you would like with JPA annotations, however without an implementation nothing will happen. Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality.

When you use Hibernate with JPA you are actually using the Hibernate JPA implementation. The benefit of this is that you can swap out Hibernate's implementation of JPA for another implementation of the JPA specification. When you use straight Hibernate you are locking into the implementation because other ORMs may use different methods/configurations and annotations, therefore you cannot just switch over to another ORM.

For a more detailed description read my blog entry.

How to input matrix (2D list) in Python?

Apart from the accepted answer, you can also initialise your rows in the following manner - matrix[i] = [0]*n

Therefore, the following piece of code will work -

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
    matrix += [0]
# initialize the matrix
for i in range (0,m):
    matrix[i] = [0]*n
for i in range (0,m):
    for j in range (0,n):
        print ('entry in row: ',i+1,' column: ',j+1)
        matrix[i][j] = int(input())
print (matrix)

Catch Ctrl-C in C

Addendum regarding UN*X platforms.

According to the signal(2) man page on GNU/Linux, the behavior of signal is not as portable as behavior of sigaction:

The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.

On System V, system did not block delivery of further instances of the signal and delivery of a signal would reset the handler to the default one. In BSD the semantics changed.

The following variation of previous answer by Dirk Eddelbuettel uses sigaction instead of signal:

#include <signal.h>
#include <stdlib.h>

static bool keepRunning = true;

void intHandler(int) {
    keepRunning = false;
}

int main(int argc, char *argv[]) {
    struct sigaction act;
    act.sa_handler = intHandler;
    sigaction(SIGINT, &act, NULL);

    while (keepRunning) {
        // main loop
    }
}

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

JTable How to refresh table model after insert delete or update the data.

I did it like this in my Jtable its autorefreshing after 300 ms;

DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
                return false;
            }
};
JTable table = new JTable();

Timer t = new Timer(300, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                addColumns();
                remakeData(set);
                table.setModel(model);
            }
        });
        t.start();

private void addColumns() {
        model.setColumnCount(0);
        model.addColumn("NAME");
            model.addColumn("EMAIL");} 

 private void remakeData(CollectionType< Objects > name) {
    model.setRowCount(0);
    for (CollectionType Objects : name){
    String n = Object.getName();
    String e = Object.getEmail();
    model.insertRow(model.getRowCount(),new Object[] { n,e });
    }}

I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange

How to stop INFO messages displaying on spark console?

Answers above are correct but didn't exactly help me as there was additional information I required.

I have just setup Spark so the log4j file still had the '.template' suffix and wasn't being read. I believe that logging then defaults to Spark core logging conf.

So if you are like me and find that the answers above didn't help, then maybe you too have to remove the '.template' suffix from your log4j conf file and then the above works perfectly!

http://apache-spark-user-list.1001560.n3.nabble.com/disable-log4j-for-spark-shell-td11278.html

Can you call Directory.GetFiles() with multiple filters?

Using GetFiles search pattern for filtering the extension is not safe!! For instance you have two file Test1.xls and Test2.xlsx and you want to filter out xls file using search pattern *.xls, but GetFiles return both Test1.xls and Test2.xlsx I was not aware of this and got error in production environment when some temporary files suddenly was handled as right files. Search pattern was *.txt and temp files was named *.txt20181028_100753898 So search pattern can not be trusted, you have to add extra check on filenames as well.

How to get Device Information in Android

You can use the Build Class to get the device information.

For example:

String myDeviceModel = android.os.Build.MODEL;

How to get text in QlineEdit when QpushButton is pressed in a string?

The object name is not very important. what you should be focusing at is the variable that stores the lineedit object (le) and your pushbutton object(pb)

QObject(self.pb, SIGNAL("clicked()"), self.button_clicked)

def button_clicked(self):
  self.le.setText("shost")

I think this is what you want. I hope i got your question correctly :)

SQL query to group by day

For SQL Server:

GROUP BY datepart(year,datefield), 
    datepart(month,datefield), 
    datepart(day,datefield)

or faster (from Q8-Coder):

GROUP BY dateadd(DAY,0, datediff(day,0, created))

For MySQL:

GROUP BY year(datefield), month(datefield), day(datefield)

or better (from Jon Bright):

GROUP BY date(datefield)

For Oracle:

GROUP BY to_char(datefield, 'yyyy-mm-dd')

or faster (from IronGoofy):

GROUP BY trunc(created);

For Informix (by Jonathan Leffler):

GROUP BY date_column
GROUP BY EXTEND(datetime_column, YEAR TO DAY)

How can I call the 'base implementation' of an overridden virtual method?

It's impossible if the method is declared in the derived class as overrides. to do that, the method in the derived class should be declared as new:

public class Base {

    public virtual string X() {
        return "Base";
    }
}
public class Derived1 : Base
{
    public new string X()
    {
        return "Derived 1";
    }
}

public class Derived2 : Base 
{
    public override string X() {
        return "Derived 2";
    }
}

Derived1 a = new Derived1();
Base b = new Derived1();
Base c = new Derived2();
a.X(); // returns Derived 1
b.X(); // returns Base
c.X(); // returns Derived 2

See fiddle here

Display Records From MySQL Database using JTable in Java

this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project and do that : 1- creat a connection 2- statment and resultset 3- creat a jtable 4- give the result set to DbUtils.resultSetToTableModel(rs) as define in this methode you well get your jtable so easy.

public void afficherAll(String tableName){
        String sql="select * from "+tableName;
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery(sql);
            tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
             JOptionPane.showMessageDialog(null, e);
        }       
    }

How to get an IFrame to be responsive in iOS Safari?

I needed a cross-browser solution. Requirements were:

  • needed to work on both iOS and elsewhere
  • don't have access to the content in the iFrame
  • need it to scroll!

Building off what I learned from @Idra regarding scrolling="no" on iOS and this post about fitting iFrame content to the screen in iOS here's what I ended up with. Hope it helps someone =)

HTML

<div id="url-wrapper"></div>

CSS

html, body{
    height: 100%;
}

#url-wrapper{
    margin-top: 51px;
    height: 100%;
}

#url-wrapper iframe{
    height: 100%;
    width: 100%;
}

#url-wrapper.ios{
    overflow-y: auto;
    -webkit-overflow-scrolling:touch !important;
    height: 100%;
}

#url-wrapper.ios iframe{
    height: 100%;
    min-width: 100%;
    width: 100px;
    *width: 100%;
}

JS

function create_iframe(url){

    var wrapper = jQuery('#url-wrapper');

    if(navigator.userAgent.match(/(iPod|iPhone|iPad)/)){
        wrapper.addClass('ios');
        var scrolling = 'no';
    }else{
        var scrolling = 'yes';
    }

    jQuery('<iframe>', {
        src: url,
        id:  'url',
        frameborder: 0,
        scrolling: scrolling
    }).appendTo(wrapper);

}

Returning binary file from controller in ASP.NET Web API

You could try

httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");

How do I parse JSON with Objective-C?

  1. I recommend and use TouchJSON for parsing JSON.
  2. To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:

    NSDictionary *userinfo=[jsondic valueforKey:@"#data"];
    NSDictionary *user;
    NSInteger i = 0;
    NSString *skey;
    if(userinfo != nil){
        for( i = 0; i < [userinfo count]; i++ ) {
            if(i)
                skey = [NSString stringWithFormat:@"%d",i];
            else
                skey = @"";
    
            user = [userinfo objectForKey:skey];
            NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]);
            NSLog(@"last_name:%@",[user objectForKey:@"last_name"]);
            NSLog(@"first_name:%@",[user objectForKey:@"first_name"]);
            NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]);
        }
    }
    

How to get current SIM card number in Android?

You have everything right, but the problem is with getLine1Number() function.

getLine1Number()- this method returns the phone number string for line 1, i.e the MSISDN for a GSM phone. Return null if it is unavailable.

this method works only for few cell phone but not all phones.

So, if you need to perform operations according to the sim(other than calling), then you should use getSimSerialNumber(). It is always unique, valid and it always exists.

Role/Purpose of ContextLoaderListener in Spring?

When you want to put your Servlet file in your custom location or with custom name, rather than the default naming convention [servletname]-servlet.xml and path under Web-INF/ ,then you can use ContextLoaderListener.

How to refresh token with Google API client?

Had the same issue; my script that worked yesterday, for some odd reason did not today. No changes.

Apparently this was because my system clock was off by 2.5 (!!) seconds, syncing with NTP fixed it.

See also: https://code.google.com/p/google-api-php-client/wiki/OAuth2#Solving_invalid_grant_errors

Set field value with reflection

The method below sets a field on your object even if the field is in a superclass

/**
 * Sets a field value on a given object
 *
 * @param targetObject the object to set the field value on
 * @param fieldName    exact name of the field
 * @param fieldValue   value to set on the field
 * @return true if the value was successfully set, false otherwise
 */
public static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}

htaccess remove index.php from url

try this, it work for me

_x000D_
_x000D_
<IfModule mod_rewrite.c>

# Enable Rewrite Engine
# ------------------------------
RewriteEngine On
RewriteBase /

# Redirect index.php Requests
# ------------------------------
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteCond %{THE_REQUEST} !/system/.*
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,L]

# Standard ExpressionEngine Rewrite
# ------------------------------
RewriteCond $1 !\.(css|js|gif|jpe?g|png) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

</IfModule>
_x000D_
_x000D_
_x000D_

MySQL string replace

The replace function should work for you.

REPLACE(str,from_str,to_str)

Returns the string str with all occurrences of the string from_str replaced by the string to_str. REPLACE() performs a case-sensitive match when searching for from_str.

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

Filtering array of objects with lodash based on property value

_x000D_
_x000D_
let myArr = [_x000D_
    { name: "john", age: 23 },_x000D_
    { name: "john", age: 43 },_x000D_
    { name: "jim", age: 101 },_x000D_
    { name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
// this will return old object (myArr) with items named 'john'_x000D_
let list = _.filter(myArr, item => item.name === 'jhon');_x000D_
_x000D_
//  this will return new object referenc (new Object) with items named 'john' _x000D_
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
_x000D_
_x000D_
_x000D_

Find and extract a number from a string

 string input = "Hello 20, I am 30 and he is 40";
 var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();

How can a LEFT OUTER JOIN return more records than exist in the left table?

Table1                Table2
_______               _________
1                      2
2                      2
3                      5
4                      6

SELECT Table1.Id, Table2.Id FROM Table1 LEFT OUTER JOIN Table2 ON Table1.Id=Table2.Id

Results:

1,null
2,2
2,2
3,null
4,null

Multiple Cursors in Sublime Text 2 Windows

Mac Users, let me save you the time:

  • Cmd+a: select the lines you want a cursor
  • Cmd+Shift+l: to create the cursor

How to determine the first and last iteration in a foreach loop?

Try this:

function children( &$parents, $parent, $selected ){
  if ($parents[$parent]){
    $list = '<ul>';
    $counter = count($parents[$parent]);
    $class = array('first');
    foreach ($parents[$parent] as $child){
      if ($child['id'] == $selected)  $class[] = 'active';
      if (!--$counter) $class[] = 'last';
      $list .= '<li class="' . implode(' ', $class) . '"><div><a href="]?id=' . $child['id'] . '" alt="' . $child['name'] . '">' . $child['name'] . '</a></div></li>';
      $class = array();
      $list .= children($parents, $child['id'], $selected);
    }
    $list .= '</ul>';
    return $list;
  }
}
$output .= children( $parents, 0, $p_industry_id);

phonegap open link in browser

I also faced the issue that link was not opening on browser here is my fix with steps:

1: Install this cordova plugin.

cordova plugin add cordova-plugin-inappbrowser

2: add the open link in the html like following.

<a href="#" onclick="window.open('https://www.google.com/', '_system', 'location=yes');" >Google</a>

3: this is the most importaint step due to this I faced lots of issue: download the cordova.js file and paste it in the www folder. Then make a reference of this in the index.html file.

<script src="cordova.js"></script>

This solution will work for both the environment android and iPhone.

Why is &#65279; appearing in my HTML?

Here's my 2 cents: I had the same problem and I tried using Notepad++ to convert to UTF-8 no BOM, and also the old "copy to MS notepad then back again" trick, all to no avail. My problem was solved by making sure all files (and 'included' files) were the same file system; I had some files that were Windows format and some that had been copied off a remote Linux server, so were in UNIX format.

How to enable CORS on Firefox?

It's only possible when the server sends this header: Access-Control-Allow-Origin: *

If this is your code then you can setup it like this (PHP):

header('Access-Control-Allow-Origin: *');

The tilde operator in Python

I was solving this leetcode problem and I came across this beautiful solution by a user named Zitao Wang.

The problem goes like this for each element in the given array find the product of all the remaining numbers without making use of divison and in O(n) time

The standard solution is:

Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
        and then multiplying them for the final answer 

His solution uses only one for loop by making use of. He computes the left product and right product on the fly using ~

def productExceptSelf(self, nums):
    res = [1]*len(nums)
    lprod = 1
    rprod = 1
    for i in range(len(nums)):
        res[i] *= lprod
        lprod *= nums[i]
        res[~i] *= rprod
        rprod *= nums[~i]
    return res

Removing "bullets" from unordered list <ul>

Try this it works

<ul class="sub-menu" type="none">
           <li class="sub-menu-list" ng-repeat="menu in list.components">
               <a class="sub-menu-link">
                   {{ menu.component }}
               </a>
           </li>
        </ul>

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

Fatal error: "No Target Architecture" in Visual Studio

Solve it by placing the following include files and definition first:

#define WIN32_LEAN_AND_MEAN      // Exclude rarely-used stuff from Windows headers

#include <windows.h>

Count items in a folder with PowerShell

Recursively count files in directories in PowerShell 2.0

ls -rec | ? {$_.mode -match 'd'} | select FullName,  @{N='Count';E={(ls $_.FullName | measure).Count}}

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

How do I compile and run a program in Java on my Mac?

Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/

Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/


Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:

  • The source code editor
    • With syntax highlighting, colors and other visual cues
    • Easy cross-referencing to the documentation to facilitate learning
  • Compiler
    • Run the code with one click
    • Get notified of errors/mistakes as you go

As you gain more experience, you'll start to appreciate the rest of its rich set of features.

Android YouTube app Play Video Intent

Use my code .. I am able to play youtube video using this code ... you just need to provide youtube video id in the "videoId" variable ....

String videoId = "Fee5vbFLYM4";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId)); 
intent.putExtra("VIDEO_ID", videoId); 
startActivity(intent); 

How can I change the thickness of my <hr> tag

I suggest to use construction like

<style>
  .hr { height:0; border-top:1px solid _anycolor_; }
  .hr hr { display:none }
</style>

<div class="hr"><hr /></div>

How to get image height and width using java?

Here is something very simple and handy.

BufferedImage bimg = ImageIO.read(new File(filename));
int width          = bimg.getWidth();
int height         = bimg.getHeight();

Intellij JAVA_HOME variable

Right Click On Project -> Open Module Settings -> Click SDK's

enter image description here

Choose Java Home Directory

How do I perform an IF...THEN in an SQL SELECT?

The case statement is your friend in this situation, and takes one of two forms:

The simple case:

SELECT CASE <variable> WHEN <value>      THEN <returnvalue>
                       WHEN <othervalue> THEN <returnthis>
                                         ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

The extended case:

SELECT CASE WHEN <test>      THEN <returnvalue>
            WHEN <othertest> THEN <returnthis>
                             ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

You can even put case statements in an order by clause for really fancy ordering.

Cannot get OpenCV to compile because of undefined references?

If you do the following, you will be able to use opencv build from OpenCV_INSTALL_PATH.

cmake_minimum_required(VERSION 2.8)

SET(OpenCV_INSTALL_PATH /home/user/opencv/opencv-2.4.13/release/)

SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")

LINK_DIRECTORIES(${OpenCV_LIB_DIR})

set(OpenCV_LIBS opencv_core opencv_imgproc opencv_calib3d opencv_video opencv_features2d opencv_ml opencv_highgui opencv_objdetect opencv_contrib opencv_legacy opencv_gpu)

# find_package( OpenCV )

project(edge.cpp)

add_executable(edge edge.cpp)

htaccess "order" Deny, Allow, Deny

Not answering OPs question directly, but for the people finding this question in search of clarity on what's the difference between allow,deny and deny,allow:

Read the comma as a "but".

  • allow but deny: whitelist with exceptions.
    everything is denied, except items on the allow list, except items on the deny list
  • deny but allow: blacklist with exceptions.
    everything is allowed, except items on the deny list, except items on the allow list

allow only one country access, but exclude proxies within this country

OP needed a whitelist with exceptions, therefore allow,deny instead of deny,allow

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Java 6 ships the javax.xml.bind.DatatypeConverter. This class provides two static methods that support the same decoding & encoding:

parseBase64Binary() / printBase64Binary()

Update: Since Java 8 we now have a much better Base64 Support.

Use this and you will not need an extra library, like Apache Commons Codec.

Only numbers. Input number in React

one line of code

<input value={this.state.financialGoal} onChange={event => this.setState({financialGoal: event.target.value.replace(/\D/,'')})}/>

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

Windows equivalent of OS X Keychain?

It is year 2018, and Windows 10 has a "Credential Manager" that can be found in "Control Panel"

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.

Get difference between 2 dates in JavaScript?

var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 

alert(diffDays )

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Lodash remove duplicates from array

Or simply Use union, for simple array.

_.union([1,2,3,3], [3,5])

// [1,2,3,5]

How do I get client IP address in ASP.NET CORE?

Some fallback logic can be added to handle the presence of a Load Balancer.

Also, through inspection, the X-Forwarded-For header happens to be set anyway even without a Load Balancer (possibly because of additional Kestrel layer?):

public string GetRequestIP(bool tryUseXForwardHeader = true)
{
    string ip = null;

    // todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For

    // X-Forwarded-For (csv list):  Using the First entry in the list seems to work
    // for 99% of cases however it has been suggested that a better (although tedious)
    // approach might be to read each IP from right to left and use the first public IP.
    // http://stackoverflow.com/a/43554000/538763
    //
    if (tryUseXForwardHeader)
        ip = GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();

    // RemoteIpAddress is always null in DNX RC1 Update1 (bug).
    if (ip.IsNullOrWhitespace() && _httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress != null)
        ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

    if (ip.IsNullOrWhitespace())
        ip = GetHeaderValueAs<string>("REMOTE_ADDR");

    // _httpContextAccessor.HttpContext?.Request?.Host this is the local host.

    if (ip.IsNullOrWhitespace())
        throw new Exception("Unable to determine caller's IP.");

    return ip;
}

public T GetHeaderValueAs<T>(string headerName)
{
    StringValues values;

    if (_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName, out values) ?? false)
    {
        string rawValues = values.ToString();   // writes out as Csv when there are multiple.

        if (!rawValues.IsNullOrWhitespace())
            return (T)Convert.ChangeType(values.ToString(), typeof(T));
    }
    return default(T);
}

public static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
{
    if (string.IsNullOrWhiteSpace(csvList))
        return nullOrWhitespaceInputReturnsNull ? null : new List<string>();

    return csvList
        .TrimEnd(',')
        .Split(',')
        .AsEnumerable<string>()
        .Select(s => s.Trim())
        .ToList();
}

public static bool IsNullOrWhitespace(this string s)
{
    return String.IsNullOrWhiteSpace(s);
}

Assumes _httpContextAccessor was provided through DI.

How to access Winform textbox control from another class?

Form frm1 = new Form1();
frm1.Controls.Find("control_name",true)[0].Text = "I changed this from another form";

How to disable manual input for JQuery UI Datepicker field?

When you make the input, set it to be readonly.

<input type="text" name="datepicker" id="datepicker" readonly="readonly" />

Custom Drawable for ProgressBar/ProgressDialog

Your style should look like this:

<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
    <item name="android:indeterminateDrawable">@anim/mp3</item>
</style>

CSS pseudo elements in React

Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hover via onMouseEnter and onMouseLeave to using more elements to reproduce pseudo-elements like :after and :before to just use an external stylesheet.

Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.

Imagine a large team wherein each developer is recreating CSS features like :hover. Each developer will do it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about n ways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.

So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).

Made a solution in this space called Style It that simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after:

npm install style-it --save

Functional Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return Style.it(`
      #heart {
        position: relative;
        width: 100px;
        height: 90px;
      }
      #heart:before,
      #heart:after {
        position: absolute;
        content: "";
        left: 50px;
        top: 0;
        width: 50px;
        height: 80px;
        background: red;
        -moz-border-radius: 50px 50px 0 0;
        border-radius: 50px 50px 0 0;
        -webkit-transform: rotate(-45deg);
        -moz-transform: rotate(-45deg);
        -ms-transform: rotate(-45deg);
        -o-transform: rotate(-45deg);
        transform: rotate(-45deg);
        -webkit-transform-origin: 0 100%;
        -moz-transform-origin: 0 100%;
        -ms-transform-origin: 0 100%;
        -o-transform-origin: 0 100%;
        transform-origin: 0 100%;
      }
      #heart:after {
        left: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        -o-transform: rotate(45deg);
        transform: rotate(45deg);
        -webkit-transform-origin: 100% 100%;
        -moz-transform-origin: 100% 100%;
        -ms-transform-origin: 100% 100%;
        -o-transform-origin: 100% 100%;
        transform-origin :100% 100%;
      }
    `,
      <div id="heart" />
    );
  }
}

export default Intro;

JSX Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
      {`
        #heart {
          position: relative;
          width: 100px;
          height: 90px;
        }
        #heart:before,
        #heart:after {
          position: absolute;
          content: "";
          left: 50px;
          top: 0;
          width: 50px;
          height: 80px;
          background: red;
          -moz-border-radius: 50px 50px 0 0;
          border-radius: 50px 50px 0 0;
          -webkit-transform: rotate(-45deg);
          -moz-transform: rotate(-45deg);
          -ms-transform: rotate(-45deg);
          -o-transform: rotate(-45deg);
          transform: rotate(-45deg);
          -webkit-transform-origin: 0 100%;
          -moz-transform-origin: 0 100%;
          -ms-transform-origin: 0 100%;
          -o-transform-origin: 0 100%;
          transform-origin: 0 100%;
        }
        #heart:after {
          left: 0;
          -webkit-transform: rotate(45deg);
          -moz-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
          -o-transform: rotate(45deg);
          transform: rotate(45deg);
          -webkit-transform-origin: 100% 100%;
          -moz-transform-origin: 100% 100%;
          -ms-transform-origin: 100% 100%;
          -o-transform-origin: 100% 100%;
          transform-origin :100% 100%;
        }
     `}

      <div id="heart" />
    </Style>
  }
}

export default Intro;

Heart example pulled from CSS-Tricks

How to nicely format floating numbers to string without unnecessary decimal 0's

Format price with grouping, rounding, and no unnecessary zeroes (in double).

Rules:

  1. No zeroes at the end (2.0000 = 2; 1.0100000 = 1.01)
  2. Two digits maximum after a point (2.010 = 2.01; 0.20 = 0.2)
  3. Rounding after the 2nd digit after a point (1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0)
  4. Returns 0 (null/-0 = 0)
  5. Adds $ (= $56/-$56)
  6. Grouping (101101.02 = $101,101.02)

More examples:

-99.985 = -$99.99

10 = $10

10.00 = $10

20.01000089 = $20.01

It is written in Kotlin as a fun extension of Double (because it is used in Android), but it can be converted to Java easily, because Java classes were used.

/**
 * 23.0 -> $23
 *
 * 23.1 -> $23.1
 *
 * 23.01 -> $23.01
 *
 * 23.99 -> $23.99
 *
 * 23.999 -> $24
 *
 * -0.0 -> $0
 *
 * -5.00 -> -$5
 *
 * -5.019 -> -$5.02
 */
fun Double?.formatUserAsSum(): String {
    return when {
        this == null || this == 0.0 -> "$0"
        this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
        else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
    }
}

How to use:

var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20

yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0

About DecimalFormat: https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

How to make inactive content inside a div?

if you want to hide a whole div from the view in another screen size. You can follow bellow code as an example.

div.disabled{
  display: none;
}

Sort tuples based on second parameter

You can use the key parameter to list.sort():

my_list.sort(key=lambda x: x[1])

or, slightly faster,

my_list.sort(key=operator.itemgetter(1))

(As with any module, you'll need to import operator to be able to use it.)

What is Mocking?

Mock is a method/object that simulates the behavior of a real method/object in controlled ways. Mock objects are used in unit testing.

Often a method under a test calls other external services or methods within it. These are called dependencies. Once mocked, the dependencies behave the way we defined them.

With the dependencies being controlled by mocks, we can easily test the behavior of the method that we coded. This is Unit testing.

What is the purpose of mock objects?

Mocks vs stubs

Unit tests vs Functional tests

What is the --save option for npm install?

The easier (and more awesome) way to add dependencies to your package.json is to do so from the command line, flagging the npm install command with either --save or --save-dev, depending on how you'd like to use that dependency.

Get date from input form within PHP

Validate the INPUT.

$time = strtotime($_POST['dateFrom']);
if ($time) {
  $new_date = date('Y-m-d', $time);
  echo $new_date;
} else {
   echo 'Invalid Date: ' . $_POST['dateFrom'];
  // fix it.
}

How to trap the backspace key using jQuery?

try this one :

 $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})  

Matplotlib figure facecolor (background color)

It's because savefig overrides the facecolor for the background of the figure.

(This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!)

The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)

Hope that helps!

Using a string variable as a variable name

You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

Handling JSON Post Request in Go

I like to define custom structs locally. So:

// my handler func
func addImage(w http.ResponseWriter, r *http.Request) {

    // define custom type
    type Input struct {
        Url        string  `json:"url"`
        Name       string  `json:"name"`
        Priority   int8    `json:"priority"`
    }

    // define a var 
    var input Input

    // decode input or return error
    err := json.NewDecoder(r.Body).Decode(&input)
    if err != nil {
        w.WriteHeader(400)
        fmt.Fprintf(w, "Decode error! please check your JSON formating.")
        return
    }

    // print user inputs
    fmt.Fprintf(w, "Inputed name: %s", input.Name)

}

Android M Permissions: onRequestPermissionsResult() not being called

You can try this:

requestPermissions(permissions, PERMISSIONS_CODE);

If you are calling this code from a fragment it has it's own requestPermissions method. I believe the problem is that you are calling static method.

Pro Tip if you want the onRequestPermissionsResult() in a fragment: FragmentCompat.requestPermissions(Fragment fragment, String[] permissions, int requestCode)

Build Error - missing required architecture i386 in file

I just wanted to mention that in XCode if you go to "Edit Project Settings" and find "Search Paths" There is a field for "Framework Search Paths". Updating this should fix the problem, without having to hack the project file!

Cheers!

Jesse

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

Use the createFromFormat method:

$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);

UPDATE

I now recommend the use of Carbon

Use URI builder in Android or create URL with variables

Let's say that I want to create the following URL:

https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name

To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.myawesomesite.com")
    .appendPath("turtles")
    .appendPath("types")
    .appendQueryParameter("type", "1")
    .appendQueryParameter("sort", "relevance")
    .fragment("section-name");
String myUrl = builder.build().toString();

How to achieve pagination/table layout with Angular.js?

here i have solve my angularJS pagination issue with some more tweak in server side + view end you can check the code it will be more efficient. all i have to do is put two value start number and end number , it will represent index of the returned json array.

here is the angular

var refresh = function () {
    $('.loading').show();
    $http.get('http://put.php?OutputType=JSON&r=all&s=' + $scope.CountStart + '&l=' + $scope.CountEnd).success(function (response) {
        $scope.devices = response;


        $('.loading').hide();
    });
};

if you see carefully $scope.CountStart and $scope.CountStart are two argument i am passing with the api

here is the code for next button

$scope.nextPage = function () {
    $('.loading').css("display", "block");
    $scope.nextPageDisabled();


    if ($scope.currentPage >= 0) {
        $scope.currentPage++;

        $scope.CountStart = $scope.CountStart + $scope.DevicePerPage;
        $scope.CountEnd = $scope.CountEnd + $scope.DevicePerPage;
        refresh();
    }
};

here is the code for previous button

$scope.prevPage = function () {
    $('.loading').css("display", "block");
    $scope.nextPageDisabled();

    if ($scope.currentPage > 0) {
        $scope.currentPage--;

        $scope.CountStart = $scope.CountStart - $scope.DevicePerPage;
        $scope.CountEnd = $scope.CountEnd - $scope.DevicePerPage;

        refresh();

    }
};

if the page number is zero my previous button will be deactivated

   $scope.nextPageDisabled = function () {

    console.log($scope.currentPage);

    if ($scope.currentPage === 0) {
        return false;
    } else {
        return true;
    }
};

.attr('checked','checked') does not work

With jQuery, never use inline onclick javascript. Keep it unobtrusive. Do this instead, and remove the onclick completely.

Also, note the use of the :checked pseudo selector in the last line. The reason for this is because once the page is loaded, the html and the actual state of the form element can be different. Open a web inspector and you can click on the other radio button and the HTML will still show the first one is checked. The :checked selector instead filters elements that are actually checked, regardless of what the html started as.

$('button').click(function() {
    alert($('input[name="myname"][value="b"]').length);
    $('input[name="myname"][value="b"]').attr('checked','checked');
    $('#b').attr('checked',true);
    alert($('input[name="myname"]:checked').val());
});

http://jsfiddle.net/uL545/1/

Check if space is in a string

You can say word.strip(" ") to remove any leading/trailing spaces from the string - you should do that before your if statement. That way if someone enters input such as " test " your program will still work.

That said, if " " in word: will determine if a string contains any spaces. If that does not working, can you please provide more information?

Dockerfile copy keep subdirectory structure

Remove star from COPY, with this Dockerfile:

FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*

Structure is there:

$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon 
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : COPY files/ /files/
 ---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
 ---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2

/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root    0 May 13 16:04 file1
-rw-r--r-- 1 root root    0 May 13 16:04 file2
 ---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b

How to create dictionary and add key–value pairs dynamically?

var dict = []; // create an empty array

dict.push({
    key:   "keyName",
    value: "the value"
});
// repeat this last part as needed to add more key/value pairs

Basically, you're creating an object literal with 2 properties (called key and value) and inserting it (using push()) into the array.


Edit: So almost 5 years later, this answer is getting downvotes because it's not creating an "normal" JS object literal (aka map, aka hash, aka dictionary).
It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with key and value properties. Don't ask me why that structure was required, but it's the one that was asked for.

But, but, if what you want in a plain JS object - and not the structure OP asked for - see tcll's answer, though the bracket notation is a bit cumbersome if you just have simple keys that are valid JS names. You can just do this:

// object literal with properties
var dict = {
  key1: "value1",
  key2: "value2"
  // etc.
};

Or use regular dot-notation to set properties after creating an object:

// empty object literal with properties added afterward
var dict = {};
dict.key1 = "value1";
dict.key2 = "value2";
// etc.

You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:

var dict = {};

// this obviously won't work
dict.some invalid key (for multiple reasons) = "value1";

// but this will
dict["some invalid key (for multiple reasons)"] = "value1";

You also want bracket notation if your keys are dynamic:

dict[firstName + " " + lastName] = "some value";

Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g. a Date object gets converted to its string representation:

dict[new Date] = "today's value";

console.log(dict);
// => {
//      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value"
//    }

Note however that this doesn't necessarily "just work", as many objects will have a string representation like "[object Object]" which doesn't make for a non-unique key. So be wary of something like:

var objA = { a: 23 },
    objB = { b: 42 };

dict[objA] = "value for objA";
dict[objB] = "value for objB";

console.log(dict);
// => { "[object Object]": "value for objB" }

Despite objA and objB being completely different and unique elements, they both have the same basic string representation: "[object Object]".

The reason Date doesn't behave like this is that the Date prototype has a custom toString method which overrides the default string representation. And you can do the same:

// a simple constructor with a toString prototypal method
function Foo() {
  this.myRandomNumber = Math.random() * 1000 | 0;
}

Foo.prototype.toString = function () {
  return "Foo instance #" + this.myRandomNumber;
};

dict[new Foo] = "some value";

console.log(dict);
// => {
//      "Foo instance #712": "some value"
//    }

(Note that since the above uses a random number, name collisions can still occur very easily. It's just to illustrate an implementation of toString.)

So when trying to use objects as keys, JS will use the object's own toString implementation, if any, or use the default string representation.

Gradle DSL method not found: 'runProguard'

If you are migrating to 1.0.0 you need to change the following properties.

In the Project's build.gradle file you need to replace minifyEnabled.

Hence your new build type should be

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'        
    }
}

Also make sure that gradle version is 1.0.0 like

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

in the build.gradle file.

This should solve the problem.

Source: http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0

Why is Node.js single threaded?

Long story short, node draws from V8, which is internally single-threaded. There are ways to work around the constraints for CPU-intensive tasks.

At one point (0.7) the authors tried to introduce isolates as a way of implementing multiple threads of computation, but were ultimately removed: https://groups.google.com/forum/#!msg/nodejs/zLzuo292hX0/F7gqfUiKi2sJ

How to set header and options in axios?

You can send a get request with Headers (for authentication with jwt for example):

axios.get('https://example.com/getSomething', {
 headers: {
   Authorization: 'Bearer ' + token //the token is a variable which holds the token
 }
})

Also you can send a post request.

axios.post('https://example.com/postSomething', {
 email: varEmail, //varEmail is a variable which holds the email
 password: varPassword
},
{
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})

My way of doing it,is to set a request like this:

 axios({
  method: 'post', //you can set what request you want to be
  url: 'https://example.com/request',
  data: {id: varID},
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})

Change the Textbox height?

Steps:

  1. Set the textboxes to multiline
  2. Change the height
  3. Change the font size. (so it fit into the big textboxes)
  4. Set the textboxes back to non-multiline

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="any" />

It won't have validation problems and the arrows will have step of "1"

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):

<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step

JavaScript ternary operator example with functions

Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best...

x = (1 < 2) ? true : false;

The use of ternary here is totally unnecessary - you could simply write

x = (1 < 2);

Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, and therefore you can express:

(IsChecked == true) ? removeItem($this) : addItem($this);

Simply as:

(IsChecked) ? removeItem($this) : addItem($this);

In fact, I would also remove the IsChecked temporary as well which leaves you with:

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

As for whether this is acceptable syntax, it sure is! It's a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)

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

Update

The below made sense for 2013. However, now, I would use the :not() selector as described below.


CSS can be overwritten.

DEMO: http://jsfiddle.net/persianturtle/J4SUb/

Use this:

_x000D_
_x000D_
.parent {
  padding: 50px;
  border: 1px solid black;
}

.parent span {
  position: absolute;
  top: 200px;
  padding: 30px;
  border: 10px solid green;
}

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

.parent span:hover {
  border: 10px solid green;
}
_x000D_
<a class="parent">
    Parent text
    <span>Child text</span>    
</a>
_x000D_
_x000D_
_x000D_

How to access ssis package variables inside script component

First List the Variable that you want to use them in Script task at ReadOnlyVariables in the Script task editor and Edit the Script

To use your ReadOnlyVariables in script code

String codeVariable = Dts.Variables["User::VariableNameinSSIS"].Value.ToString();

this line of code will treat the ssis package variable as a string.

html 5 audio tag width

You also can set the width of a audio tag by JavaScript:

audio = document.getElementById('audio-id');
audio.style.width = '200px';

Remove pandas rows with duplicate indices

This adds the index as a dataframe column, drops duplicates on that, then removes the new column:

df = df.reset_index().drop_duplicates(subset='index', keep='last').set_index('index').sort_index()

Note that the use of .sort_index() above at the end is as needed and is optional.

Pass props to parent component in React.js

Edit: see the end examples for ES6 updated examples.

This answer simply handle the case of direct parent-child relationship. When parent and child have potentially a lot of intermediaries, check this answer.

Other solutions are missing the point

While they still work fine, other answers are missing something very important.

Is there not a simple way to pass a child's props to its parent using events, in React.js?

The parent already has that child prop!: if the child has a prop, then it is because its parent provided that prop to the child! Why do you want the child to pass back the prop to the parent, while the parent obviously already has that prop?

Better implementation

Child: it really does not have to be more complicated than that.

var Child = React.createClass({
  render: function () {
    return <button onClick={this.props.onClick}>{this.props.text}</button>;
  },
});

Parent with single child: using the value it passes to the child

var Parent = React.createClass({
  getInitialState: function() {
     return {childText: "Click me! (parent prop)"};
  },
  render: function () {
    return (
      <Child onClick={this.handleChildClick} text={this.state.childText}/>
    );
  },
  handleChildClick: function(event) {
     // You can access the prop you pass to the children 
     // because you already have it! 
     // Here you have it in state but it could also be
     //  in props, coming from another parent.
     alert("The Child button text is: " + this.state.childText);
     // You can also access the target of the click here 
     // if you want to do some magic stuff
     alert("The Child HTML is: " + event.target.outerHTML);
  }
});

JsFiddle

Parent with list of children: you still have everything you need on the parent and don't need to make the child more complicated.

var Parent = React.createClass({
  getInitialState: function() {
     return {childrenData: [
         {childText: "Click me 1!", childNumber: 1},
         {childText: "Click me 2!", childNumber: 2}
     ]};
  },
  render: function () {
    var children = this.state.childrenData.map(function(childData,childIndex) {
        return <Child onClick={this.handleChildClick.bind(null,childData)} text={childData.childText}/>;
    }.bind(this));
    return <div>{children}</div>;
  },

  handleChildClick: function(childData,event) {
     alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
     alert("The Child HTML is: " + event.target.outerHTML);
  }
});

JsFiddle

It is also possible to use this.handleChildClick.bind(null,childIndex) and then use this.state.childrenData[childIndex]

Note we are binding with a null context because otherwise React issues a warning related to its autobinding system. Using null means you don't want to change the function context. See also.

About encapsulation and coupling in other answers

This is for me a bad idea in term of coupling and encapsulation:

var Parent = React.createClass({
  handleClick: function(childComponent) {
     // using childComponent.props
     // using childComponent.refs.button
     // or anything else using childComponent
  },
  render: function() {
    <Child onClick={this.handleClick} />
  }
});

Using props: As I explained above, you already have the props in the parent so it's useless to pass the whole child component to access props.

Using refs: You already have the click target in the event, and in most case this is enough. Additionnally, you could have used a ref directly on the child:

<Child ref="theChild" .../>

And access the DOM node in the parent with

React.findDOMNode(this.refs.theChild)

For more advanced cases where you want to access multiple refs of the child in the parent, the child could pass all the dom nodes directly in the callback.

The component has an interface (props) and the parent should not assume anything about the inner working of the child, including its inner DOM structure or which DOM nodes it declares refs for. A parent using a ref of a child means that you tightly couple the 2 components.

To illustrate the issue, I'll take this quote about the Shadow DOM, that is used inside browsers to render things like sliders, scrollbars, video players...:

They created a boundary between what you, the Web developer can reach and what’s considered implementation details, thus inaccessible to you. The browser however, can traipse across this boundary at will. With this boundary in place, they were able to build all HTML elements using the same good-old Web technologies, out of the divs and spans just like you would.

The problem is that if you let the child implementation details leak into the parent, you make it very hard to refactor the child without affecting the parent. This means as a library author (or as a browser editor with Shadow DOM) this is very dangerous because you let the client access too much, making it very hard to upgrade code without breaking retrocompatibility.

If Chrome had implemented its scrollbar letting the client access the inner dom nodes of that scrollbar, this means that the client may have the possibility to simply break that scrollbar, and that apps would break more easily when Chrome perform its auto-update after refactoring the scrollbar... Instead, they only give access to some safe things like customizing some parts of the scrollbar with CSS.

About using anything else

Passing the whole component in the callback is dangerous and may lead novice developers to do very weird things like calling childComponent.setState(...) or childComponent.forceUpdate(), or assigning it new variables, inside the parent, making the whole app much harder to reason about.


Edit: ES6 examples

As many people now use ES6, here are the same examples for ES6 syntax

The child can be very simple:

const Child = ({
  onClick, 
  text
}) => (
  <button onClick={onClick}>
    {text}
  </button>
)

The parent can be either a class (and it can eventually manage the state itself, but I'm passing it as props here:

class Parent1 extends React.Component {
  handleChildClick(childData,event) {
     alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
     alert("The Child HTML is: " + event.target.outerHTML);
  }
  render() {
    return (
      <div>
        {this.props.childrenData.map(child => (
          <Child
            key={child.childNumber}
            text={child.childText} 
            onClick={e => this.handleChildClick(child,e)}
          />
        ))}
      </div>
    );
  }
}

But it can also be simplified if it does not need to manage state:

const Parent2 = ({childrenData}) => (
  <div>
     {childrenData.map(child => (
       <Child
         key={child.childNumber}
         text={child.childText} 
         onClick={e => {
            alert("The Child button data is: " + child.childText + " - " + child.childNumber);
                    alert("The Child HTML is: " + e.target.outerHTML);
         }}
       />
     ))}
  </div>
)

JsFiddle


PERF WARNING (apply to ES5/ES6): if you are using PureComponent or shouldComponentUpdate, the above implementations will not be optimized by default because using onClick={e => doSomething()}, or binding directly during the render phase, because it will create a new function everytime the parent renders. If this is a perf bottleneck in your app, you can pass the data to the children, and reinject it inside "stable" callback (set on the parent class, and binded to this in class constructor) so that PureComponent optimization can kick in, or you can implement your own shouldComponentUpdate and ignore the callback in the props comparison check.

You can also use Recompose library, which provide higher order components to achieve fine-tuned optimisations:

// A component that is expensive to render
const ExpensiveComponent = ({ propA, propB }) => {...}

// Optimized version of same component, using shallow comparison of props
// Same effect as React's PureRenderMixin
const OptimizedComponent = pure(ExpensiveComponent)

// Even more optimized: only updates if specific prop keys have changed
const HyperOptimizedComponent = onlyUpdateForKeys(['propA', 'propB'])(ExpensiveComponent)

In this case you could optimize the Child component by using:

const OptimizedChild = onlyUpdateForKeys(['text'])(Child)

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

Best Practice: Access form elements by HTML id or name attribute?

My answer will differ on the exact question. If I want to access a certain element specifically, then will I use document.getElementById(). An example is computing the full name of a person, because it is building on multiple fields, but it is a repeatable formula.

If I want to access the element as part of a functional structure (a form), then will I use:

var frm = document.getElementById('frm_name');
for(var i = 0; i < frm.elements.length;i++){
   ..frm.elements[i]..

This is how it also works from the perspective of the business. Changes within the loop go along with functional changes in the application and are therefor meaningful. I apply it mostly for user friendly validation and preventing network calls for checking wrong data. I repeat the validation server side (and add there some more to it), but if I can help the user client side, then is that beneficial to all.

For aggregation of data (like building a pie chart based on data in the form) I use configuration documents and custom made Javascript objects. Then is the exact meaning of the field important in relation to its context and do I use document.getElementById().

matplotlib colorbar in each subplot

In plt.colorbar(z1_plot,cax=ax1), use ax= instead of cax=, i.e. plt.colorbar(z1_plot,ax=ax1)

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

Scroll to bottom of Div on page load (jQuery)

You can check scrollHeight and clientHeight with scrollTop to scroll to bottom of div like code below.

_x000D_
_x000D_
$('#div').scroll(function (event) {_x000D_
  if ((parseInt($('#div')[0].scrollHeight) - parseInt(this.clientHeight)) == parseInt($('#div').scrollTop())) _x000D_
  {_x000D_
    console.log("this is scroll bottom of div");_x000D_
  }_x000D_
  _x000D_
});
_x000D_
_x000D_
_x000D_

VBoxManage: error: Failed to create the host-only adapter

Windows 10 Pro VirtualBox 5.2.12

In my case I had to edit the Host Only Ethernet Adapter in the VirtualBox GUI. Click Global Tools -> Host Network Manager -> Select the ethernet adapter, then click Properties. Mine was set to configure automatically, and the IP address it was trying to use was different than what I was trying to use with drupal-vm and vagrant. I just had to change that to manual and correct the IP address. I hope this helps someone else.

How can I find WPF controls by name or type?

I have a sequence function like this (which is completely general):

    public static IEnumerable<T> SelectAllRecursively<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> func)
    {
        return (items ?? Enumerable.Empty<T>()).SelectMany(o => new[] { o }.Concat(SelectAllRecursively(func(o), func)));
    }

Getting immediate children:

    public static IEnumerable<DependencyObject> FindChildren(this DependencyObject obj)
    {
        return Enumerable.Range(0, VisualTreeHelper.GetChildrenCount(obj))
            .Select(i => VisualTreeHelper.GetChild(obj, i));
    }

Finding all children down the hiararchical tree:

    public static IEnumerable<DependencyObject> FindAllChildren(this DependencyObject obj)
    {
        return obj.FindChildren().SelectAllRecursively(o => o.FindChildren());
    }

You can call this on the Window to get all controls.

After you have the collection, you can use LINQ (i.e. OfType, Where).

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

Programmatically scroll to a specific position in an Android ListView

You need two things to precisely define the scroll position of a listView:

To get the current listView Scroll position:

int firstVisiblePosition = listView.getFirstVisiblePosition(); 
int topEdge=listView.getChildAt(0).getTop(); //This gives how much the top view has been scrolled.

To set the listView Scroll position:

listView.setSelectionFromTop(firstVisiblePosition,0);
// Note the '-' sign for scrollTo.. 
listView.scrollTo(0,-topEdge);

What is SuppressWarnings ("unchecked") in Java?

@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Override and @Deprecated in Java 1.5.

@SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated.

You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.

Read more: https://javarevisited.blogspot.com/2015/09/what-is-suppresswarnings-annotation-in-java-unchecked-raw-serial.html#ixzz5rqQaOLUa

Creating a JavaScript cookie on a domain and reading it across sub domains

Just set the domain and path attributes on your cookie, like:

<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
                  + ";domain=.example.com;path=/";
</script>

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

Assuming you are on Windows (this bug is caused by the crappy bat files escaping), It is a bug introduced in the latest versions (7.0.56 and 8.0.14) to workaround another bug. Try to remove the " around the JAVA_OPTS declaration in catalina.bat. It fixed it for me with Tomcat 7.0.56 yesterday.

In 7.0.56 in bin/catalina.bat:179 and 184

:noJuliConfig
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%"

..

:noJuliManager
set "JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%"

to

:noJuliConfig
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%

.. 

:noJuliManager
set JAVA_OPTS=%JAVA_OPTS% %LOGGING_MANAGER%

For your asterisk, it might only be a configuration of yours somewhere that appends it to the host declaration.

I saw this on Tomcat's bugtracker yesterday but I can't find the link again. Edit Found it! https://issues.apache.org/bugzilla/show_bug.cgi?id=56895

I hope it fixes your problem.

$lookup on ObjectId's in an array

Aggregating with $lookup and subsequent $group is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate() to fetch those documents:

var mongoose = require("mongoose"),
    Schema = mongoose.Schema;

var productSchema = Schema({ ... });

var orderSchema = Schema({
  _id     : Number,
  products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});

var Product = mongoose.model("Product", productSchema);
var Order   = mongoose.model("Order", orderSchema);

...

Order
    .find(...)
    .populate("products")
    ...

How to get Locale from its String representation in Java?

Option 1 :

org.apache.commons.lang3.LocaleUtils.toLocale("en_US")

Option 2 :

Locale.forLanguageTag("en-US")

Please note Option 1 is "underscore" between language and country , and Option 2 is "dash".

Box shadow in IE7 and IE8

You could try this

box-shadow:
progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=10, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=10, OffY=20, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=20, OffY=30, Color='#19000000'), 
progid:DXImageTransform.Microsoft.dropshadow(OffX=30, OffY=40, Color='#19000000');

how to get file path from sd card in android

this code helps to get it easily............

Actually in some devices external sdcard default name is showing as extSdCard and for other it is sdcard1. This code snippet helps to find out that exact path and helps to retrive you the path of external device..

String sdpath,sd1path,usbdiskpath,sd0path; 

if(new File("/storage/extSdCard/").exists()) 
{ 
  sdpath="/storage/extSdCard/";
  Log.i("Sd Cardext Path",sdpath); 
} 
if(new File("/storage/sdcard1/").exists()) 
{ 
  sd1path="/storage/sdcard1/";
  Log.i("Sd Card1 Path",sd1path); 
} 
if(new File("/storage/usbcard1/").exists()) 
{ 
  usbdiskpath="/storage/usbcard1/";
  Log.i("USB Path",usbdiskpath); 
} 
if(new File("/storage/sdcard0/").exists()) 
{ 
  sd0path="/storage/sdcard0/";
  Log.i("Sd Card0 Path",sd0path); 
}

jQuery to loop through elements with the same class

Without jQuery updated

_x000D_
_x000D_
document.querySelectorAll('.testimonial').forEach(function (element, index) {_x000D_
    element.innerHTML = 'Testimonial ' + (index + 1);_x000D_
});
_x000D_
<div class="testimonial"></div>_x000D_
<div class="testimonial"></div>
_x000D_
_x000D_
_x000D_

What are OLTP and OLAP. What is the difference between them?

OLTP: It stands for OnLine Transaction Processing and is used for managing current day to day data information.
OLAP: It stands for OnLine Analytical Processing and is used to maintain the past history of data and mainly used for data analysis, it can also be referred to as warehouse.

Why are only a few video games written in Java?

Performance issue is the first reason. When you see the kind of hyper optimized C++ code that are in the Quake engines ( http://www.codemaestro.com/reviews/9 ), you know they're not gonna waste their time with a virtual machine.

Sure there may be some .NET games (which ones ? I'm interested. Are there some really CPU/GPU-intensive ones ?), but I guess it's more because lot of people are experts in MS technologies and followed Microsoft when they launched their new technology.

Oh and cross-platform just isn't in the mind of video games companies. Linux is just around 1% of market, Mac OS a few % more. They definitely think it's not worth dumping Windows-only technologies and librairies such as DirectX.

Synchronous request in Node.js

As of 2018 and using ES6 modules and Promises, we can write a function like that :

import { get } from 'http';

export const fetch = (url) => new Promise((resolve, reject) => {
  get(url, (res) => {
    let data = '';
    res.on('end', () => resolve(data));
    res.on('data', (buf) => data += buf.toString());
  })
    .on('error', e => reject(e));
});

and then in another module

let data;
data = await fetch('http://www.example.com/api_1.php');
// do something with data...
data = await fetch('http://www.example.com/api_2.php');
// do something with data
data = await fetch('http://www.example.com/api_3.php');
// do something with data

The code needs to be executed in an asynchronous context (using async keyword)

What to do about Eclipse's "No repository found containing: ..." error messages?

What I did was:

  1. I went to Window > Preferences > Install/Update > Available Software Sites, then for each enabled site I added a / to the end of the URL (if it wasn't there already), then clicked Reload as per @Hunternif answer. But the problem still persisted.
  2. Then I disabled all the software sites and re-enalbed them one by one and ran updates to keep only those that worked. After step 2. the problem was solved. Now I have enabled only the update sites that do not give the error and updates work.

How to get max value of a column using Entity Framework?

In VB.Net it would be

Dim maxAge As Integer = context.Persons.Max(Function(p) p.Age)

How can I list all tags for a Docker image on a remote registry?

You can list all the tags with skopeo and jq for json parsing through cli.

skopeo --override-os linux inspect docker://httpd | jq '.RepoTags'
[
  "2-alpine",
  "2.2-alpine",
  "2.2.29",
  "2.2.31-alpine",
  "2.2.31",
  "2.2.32-alpine",
  "2.2.32",
  "2.2.34-alpine",
  "2.2.34",
  "2.2",
  "2.4-alpine",
  "2.4.10",
  "2.4.12",
  "2.4.16",
  "2.4.17",
  "2.4.18",
  "2.4.20",
  "2.4.23-alpine",
  "2.4.23",
  "2.4.25-alpine",
  "2.4.25",
  "2.4.27-alpine",
  "2.4.27",
  "2.4.28-alpine",
  "2.4.28",
  "2.4.29-alpine",
  "2.4.29",
  "2.4.32-alpine",
  "2.4.32",
  "2.4.33-alpine",
  "2.4.33",
  "2.4.34-alpine",
  "2.4.34",
  "2.4.35-alpine",
  "2.4.35",
  "2.4.37-alpine",
  "2.4.37",
  "2.4.38-alpine",
  "2.4.38",
  "2.4.39-alpine",
  "2.4.39",
  "2.4.41-alpine",
  "2.4.41",
  "2.4.43-alpine",
  "2.4.43",
  "2.4",
  "2",
  "alpine",
  "latest"
]

For external registries:

skopeo --override-os linux inspect --creds username:password docker://<registry-url>/<repo>/<image> | jq '.RepoTags'

Note: --override-os linux is only needed if you are not running on a linux host. For example, you'll have better results with it if you are on MacOS.

LEFT OUTER JOIN in LINQ

Here's an example if you need to join more than 2 tables:

from d in context.dc_tpatient_bookingd
join bookingm in context.dc_tpatient_bookingm 
     on d.bookingid equals bookingm.bookingid into bookingmGroup
from m in bookingmGroup.DefaultIfEmpty()
join patient in dc_tpatient
     on m.prid equals patient.prid into patientGroup
from p in patientGroup.DefaultIfEmpty()

Ref: https://stackoverflow.com/a/17142392/2343

What is the inclusive range of float and double in Java?

Java's Primitive Data Types

boolean: 1-bit. May take on the values true and false only.

byte: 1 signed byte (two's complement). Covers values from -128 to 127.

short: 2 bytes, signed (two's complement), -32,768 to 32,767

int: 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.

long: 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float: 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

double: 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

char: 2 bytes, unsigned, Unicode, 0 to 65,535

How do I combine two lists into a dictionary in Python?

dict(zip([1,2,3,4], [a,b,c,d]))

If the lists are big you should use itertools.izip.

If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest.

Here, a, b, c, and d are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d'] if you want them as strings.

zip takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.

dict can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.

Remove all line breaks from a long string of text

updated based on Xbello comment:

string = my_string.rstrip('\r\n')

read more here

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

How to fast get Hardware-ID in C#?

We use a combination of the processor id number (ProcessorID) from Win32_processor and the universally unique identifier (UUID) from Win32_ComputerSystemProduct:

ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    processorId = mo["ProcessorID"] as string;
}

mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    systemId = mo["UUID"] as string;
}

var compIdStr = $"{processorId}{systemId}";

Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor") and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:

  • To be filled by O.E.M.
  • None
  • Default string

Therefore, it is worth considering this situation.

Also keep in mind that the ProcessorID number may be the same on different computers.

Change border-bottom color using jquery?

If you have this in your CSS file:

.myApp
{
    border-bottom-color:#FF0000;
}

and a div for instance of:

<div id="myDiv">test text</div>

you can use:

$("#myDiv").addClass('myApp');// to add the style

$("#myDiv").removeClass('myApp');// to remove the style

or you can just use

$("#myDiv").css( 'border-bottom-color','#FF0000');

I prefer the first example, keeping all the CSS related items in the CSS files.

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Why not just return the worksheet name with address = cell.Worksheet.Name then you can concatenate the address back on like this address = cell.Worksheet.Name & "!" & cell.Address

Given URL is not allowed by the Application configuration Facebook application error

sometimes you need to check your code (the part of redirect)

$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/xxx');
$auth_url = $helper->getLoginUrl(array('email', 'publish_actions'));
echo "<script>window.top.location.href='".$auth_url."'</script>";

if any changes happens there (for example, the name of your application "https://apps.facebook.com/xxx" in relation the application settings in facebook, you will get the above error

How to set the width of a RaisedButton in Flutter?

You can create global method like for button being used all over the app. It will resize according to the text length inside container. FittedBox widget is used to make widget fit according to the child inside it.

Widget primaryButton(String btnName, {@required Function action}) {
  return FittedBox(
  child: RawMaterialButton(
  fillColor: accentColor,
  splashColor: Colors.black12,
  elevation: 8.0,
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
  child: Container(
    padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 13.0),
    child: Center(child: Text(btnName, style: TextStyle(fontSize: 18.0))),
  ),
  onPressed: () {
    action();
   },
  ),
 );
}

If you want button of specific width and height you can use constraint property of RawMaterialButton for giving min max width and height of button

constraints: BoxConstraints(minHeight: 45.0,maxHeight:60.0,minWidth:20.0,maxWidth:150.0),

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

The first solution I can think of, is to use ViewBag to store the values that must be rendered.

Onestly I never tried if this work from a partial view, but it should imo.

How to create a service running a .exe file on Windows 2012 Server?

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

Best way to convert pdf files to tiff files

Maybe also try this? PDF Focus

This .Net library allows you to solve the problem :)

This code will help (Convert 1000 PDF files to 300-dpi TIFF files in C#):

    SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();

    string[] pdfFiles = Directory.GetFiles(@"d:\Folder with 1000 pdfs\", "*.pdf");
    string folderWithTiffs = @"d:\Folder with TIFFs\";

    foreach (string pdffile in pdfFiles)
    {
        f.OpenPdf(pdffile);

        if (f.PageCount > 0)
        {
            //save all pages to tiff files with 300 dpi
            f.ToImage(folderWithTiffs, Path.GetFileNameWithoutExtension(pdffile), System.Drawing.Imaging.ImageFormat.Tiff, 300);
        }
        f.ClosePdf();
    }

How to make rectangular image appear circular with CSS

I've been researching this very same problem and couldn't find a decent solution other than having the div with the image as background and the img tag inside of it with visibility none or something like this.

One thing I might add is that you should add a background-size: cover to the div, so that your image fills the background by clipping it's excess.

Latest jQuery version on Google's CDN

UPDATE 7/3/2014: As of now, jquery-latest.js is no longer being updated. From the jQuery blog:

We know that http://code.jquery.com/jquery-latest.js is abused because of the CDN statistics showing it’s the most popular file. That wouldn’t be the case if it was only being used by developers to make a local copy.

We have decided to stop updating this file, as well as the minified copy, keeping both files at version 1.11.1 forever.

The Google CDN team has joined us in this effort to prevent inadvertent web breakage and no longer updates the file at http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js. That file will stay locked at version 1.11.1 as well.

The following, now moot, answer is preserved here for historical reasons.


Don't do this. Seriously, don't.

Linking to major versions of jQuery does work, but it's a bad idea -- whole new features get added and deprecated with each decimal update. If you update jQuery automatically without testing your code COMPLETELY, you risk an unexpected surprise if the API for some critical method has changed.

Here's what you should be doing: write your code using the latest version of jQuery. Test it, debug it, publish it when it's ready for production.

Then, when a new version of jQuery rolls out, ask yourself: Do I need this new version in my code? For instance, is there some critical browser compatibility that didn't exist before, or will it speed up my code in most browsers?

If the answer is "no", don't bother updating your code to the latest jQuery version. Doing so might even add NEW errors to your code which didn't exist before. No responsible developer would automatically include new code from another site without testing it thoroughly.

There's simply no good reason to ALWAYS be using the latest version of jQuery. The old versions are still available on the CDNs, and if they work for your purposes, then why bother replacing them?


A secondary, but possibly more important, issue is caching. Many people link to jQuery on a CDN because many other sites do, and your users have a good chance of having that version already cached.

The problem is, caching only works if you provide a full version number. If you provide a partial version number, far-future caching doesn't happen -- because if it did, some users would get different minor versions of jQuery from the same URL. (Say that the link to 1.7 points to 1.7.1 one day and 1.7.2 the next day. How will the browser make sure it's getting the latest version today? Answer: no caching.)

In fact here's a breakdown of several options and their expiration settings...

http://code.jquery.com/jquery-latest.min.js (no cache)

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js (1 hour)

http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js (1 hour)

http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js (1 year)

So, by linking to jQuery this way, you're actually eliminating one of the major reasons to use a CDN in the first place.


http://code.jquery.com/jquery-latest.min.js may not always give you the version you expect, either. As of this writing, it links to the latest version of jQuery 1.x, even though jQuery 2.x has been released as well. This is because jQuery 1.x is compatible with older browsers including IE 6/7/8, and jQuery 2.x is not. If you want the latest version of jQuery 2.x, then (for now) you need to specify that explicitly.

The two versions have the same API, so there is no perceptual difference for compatible browsers. However, jQuery 1.x is a larger download than 2.x.

Customizing Bootstrap CSS template

you can start with this tool, https://themestr.app/theme , seeing how it overwrites the scss variables, you would get an idea what variable impacts what. its the simplest way I think.

example scss genearation:

@import url(https://fonts.googleapis.com/css?family=Montserrat:200,300,400,700);
$font-family-base:Montserrat;
@import url(https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,700);
$headings-font-family:Open Sans;

$enable-grid-classes:false;
$primary:#222222;
$secondary:#666666;
$success:#333333;
$danger:#434343;
$info:#515151;
$warning:#5f5f5f;
$light:#eceeec;
$dark:#111111;
@import "bootstrap";

Find max and second max salary for a employee table MySQL

You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know a couple of them e.g. in MySQL without using the LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM.

Generic SQL query:

SELECT
    MAX(salary)
FROM
    Employee
WHERE
    Salary NOT IN (
        SELECT
            Max(Salary)
        FROM
            Employee
    );

Another solution which uses sub query instead of NOT IN clause. It uses < operator.

SELECT
    MAX(Salary)
FROM
    Employee
WHERE
    Salary < (
        SELECT
            Max(Salary)
        FROM
            Employee
    );

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

How to listen to route changes in react router v4?

You should to use history v4 lib.

Example from there

history.listen((location, action) => {
  console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

Why is <deny users="?" /> included in the following example?

ASP.NET grants access from the configuration file as a matter of precedence. In case of a potential conflict, the first occurring grant takes precedence. So,

deny user="?" 

denies access to the anonymous user. Then

allow users="dan,matthew" 

grants access to that user. Finally, it denies access to everyone. This shakes out as everyone except dan,matthew is denied access.

Edited to add: and as @Deviant points out, denying access to unauthenticated is pointless, since the last entry includes unauthenticated as well. A good blog entry discussing this topic can be found at: Guru Sarkar's Blog

How to vertically center an image inside of a div element in HTML using CSS?

I've posted about vertical alignment it in cross-browser way (Vertically center multiple boxes with CSS)

Create one-cell table. Only table has cross-browser vertical-align

error: passing xxx as 'this' argument of xxx discards qualifiers

The objects in the std::set are stored as const StudentT. So when you try to call getId() with the const object the compiler detects a problem, mainly you're calling a non-const member function on const object which is not allowed because non-const member functions make NO PROMISE not to modify the object; so the compiler is going to make a safe assumption that getId() might attempt to modify the object but at the same time, it also notices that the object is const; so any attempt to modify the const object should be an error. Hence compiler generates an error message.

The solution is simple: make the functions const as:

int getId() const {
    return id;
}
string getName() const {
    return name;
}

This is necessary because now you can call getId() and getName() on const objects as:

void f(const StudentT & s)
{
     cout << s.getId();   //now okay, but error with your versions
     cout << s.getName(); //now okay, but error with your versions
}

As a sidenote, you should implement operator< as :

inline bool operator< (const StudentT & s1, const StudentT & s2)
{
    return  s1.getId() < s2.getId();
}

Note parameters are now const reference.

Vue.js redirection to another page

According to the docs, router.push seems like the preferred method:

To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

source: https://router.vuejs.org/en/essentials/navigation.html

FYI : Webpack & component setup, single page app (where you import the router through Main.js), I had to call the router functions by saying:

this.$router

Example: if you wanted to redirect to a route called "Home" after a condition is met:

this.$router.push('Home') 

Clearing a text field on button click

Something like this will add a button and let you use it to clear the values

<div>           
<input type="text" id="textfield1" size="5"/>         
</div>

<div>          
<input type="text" id="textfield2" size="5"/>           
</div>

<div>
    <input type="button" onclick="clearFields()" value="Clear">
</div>


<script type="text/javascript">
function clearFields() {
    document.getElementById("textfield1").value=""
    document.getElementById("textfield2").value=""
}
</script>

Send PHP variable to javascript function

Your JavaScript would have to be defined within a PHP-parsed file.

For example, in index.php you could place

<?php
$time = time();
?>
<script>
    document.write(<?php echo $time; ?>);
</script>

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Here's a way to pass a dynamic object to a view (or partial view)

Add the following class anywhere in your solution (use System namespace, so its ready to use without having to add any references) -

    namespace System
    {
        public static class ExpandoHelper
        {
            public static ExpandoObject ToExpando(this object anonymousObject)
            {
                IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
                IDictionary<string, object> expando = new ExpandoObject();
                foreach (var item in anonymousDictionary)
                    expando.Add(item);
                return (ExpandoObject)expando;
            }

        }
    }

When you send the model to the view, convert it to Expando :

    return View(new {x=4, y=6}.ToExpando());

Cheers

linux: kill background task

The following command gives you a list of all background processes in your session, along with the pid. You can then use it to kill the process.

jobs -l

Example usage:

$ sleep 300 &
$ jobs -l
[1]+ 31139 Running                 sleep 300 &
$ kill 31139

html select option SELECTED

foreach($array as $value=>$name)
{
    if($value == $_GET['sel'])
    {
         echo "<option selected='selected' value='".$value."'>".$name."</option>";
    }
    else
    {
         echo "<option value='".$value."'>".$name."</option>";
    }
}

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

There you don't need to use this.requests= when you are making get call(then requests will have observable subscription). You will get a response in observable success so setting requests value in success make sense(which you are already doing).

this._http.getRequest().subscribe(res=>this.requests=res);

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()