Programs & Examples On #Type equivalence

No plot window in matplotlib

Modern IPython uses the "--matplotlib" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.

ipython --matplotlib

Why Java Calendar set(int year, int month, int date) not returning correct date?

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

MySQL "Or" Condition

Wrap your AND logic in parenthesis, like this:

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

MySQL: is a SELECT statement case sensitive?

USE BINARY

This is a simple select

SELECT * FROM myTable WHERE 'something' = 'Something'

= 1

This is a select with binary

SELECT * FROM myTable WHERE BINARY 'something' = 'Something'

or

SELECT * FROM myTable WHERE 'something' = BINARY 'Something'

= 0

Is there any way to do HTTP PUT in python

You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:

pip install requests

More on installing requests.

Then setup the put request:

import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }

r = requests.put(url, data=json.dumps(payload), headers=headers)

See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.

Convert JSON string to dict using Python

If you trust the data source, you can use eval to convert your string into a dictionary:

eval(your_json_format_string)

Example:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>

Create own colormap using matplotlib and plot color scale

This seems to work for me.

def make_Ramp( ramp_colors ): 
    from colour import Color
    from matplotlib.colors import LinearSegmentedColormap

    color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
    plt.figure( figsize = (15,3))
    plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
    plt.xticks([])
    plt.yticks([])
    return color_ramp

custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] ) 

custom color ramp

IF...THEN...ELSE using XML

Perhaps another way to code conditional constructs in XML:

<rule>
    <if>
        <conditions>
            <condition var="something" operator="&gt;">400</condition>
            <!-- more conditions possible -->
        </conditions>
        <statements>
            <!-- do something -->
        </statements>
    </if>
    <elseif>
        <conditions></conditions>
        <statements></statements>
    </elseif>
    <else>
        <statements></statements>
    </else>
</rule>

How to merge a Series and DataFrame

If df is a pandas.DataFrame then df['new_col']= Series list_object of length len(df) will add the or Series list_object as a column named 'new_col'. df['new_col']= scalar (such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)

So a two-line code serves the purpose:

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:    
    df[x] = s[x]

Output: 
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

Creating a simple XML file using python

For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

For a Jinja example, see my answer to a similar question.

Here is an example of generating your xml with string templates.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

Output:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

See code example below:

SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String formattedDate = df.format(new Date());
out.println(formattedDate);

How to load specific image from assets with Swift

Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:

enter image description here

Split array into chunks

ES6 Generator version

function* chunkArray(array,size=1){
    var clone = array.slice(0);
    while (clone.length>0) 
      yield clone.splice(0,size); 
};
var a = new Array(100).fill().map((x,index)=>index);
for(const c of chunkArray(a,10)) 
    console.log(c);

C++ Dynamic Shared Library on Linux

Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

How to set the JDK Netbeans runs on?

Go to Tools -> Java Platforms. There, click on Add Platform, point it to C:\Program Files (x86)\Java\jdk1.6.0_25. You can either set the another JDK version or remove existing versions.

Another solution suggested in the oracle (sun) site is,

netbeans.exe --jdkhome "C:\Program Files\jdk1.6.0_20"

I tried this on 6.9.1. You may change the JDK per project as well. You need to set the available JDKs via Java Platforms dialog. Then, go to Run -> Set Project Configuration -> Customize. After that, in the opened Dialog box go to Build -> Compile. Set the version.

In Python, can I call the main() of an imported module?

I had the same need using argparse too. The thing is parse_args function of an argparse.ArgumentParser object instance implicitly takes its arguments by default from sys.args. The work around, following Martijn line, consists of making that explicit, so you can change the arguments you pass to parse_args as desire.

def main(args):
    # some stuff
    parser = argparse.ArgumentParser()
    # some other stuff
    parsed_args = parser.parse_args(args)
    # more stuff with the args

if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

The key point is passing args to parse_args function. Later, to use the main, you just do as Martijn tell.

Where does flask look for image files?

From the documentation:

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

To generate URLs for static files, use the special 'static' endpoint name:

url_for('static', filename='style.css')

The file has to be stored on the filesystem as static/style.css.

How to reset selected file with input tag file type in Angular 2?

One way to achieve it is to wrap your input in <form> tag and reset it.

I'm not considering attaching thr form to NgForm or FormControl either.

@Component({
  selector: 'form-component',
  template: `
    <form #form>
      <input type="file" placeholder="File Name" name="filename">
    </form>
    <button (click)="reset()">Reset</button>
`
})
class FormComponent {



  @ViewChild('form') form;


  reset() {
    this.form.nativeElement.reset()
  }
}

https://plnkr.co/edit/Ulqh2l093LV6GlQWKkUA?p=preview

Circle-Rectangle collision detection (intersection)

Works, just figured this out a week ago, and just now got to testing it.

double theta = Math.atan2(cir.getX()-sqr.getX()*1.0,
                          cir.getY()-sqr.getY()*1.0); //radians of the angle
double dBox; //distance from box to edge of box in direction of the circle

if((theta >  Math.PI/4 && theta <  3*Math.PI / 4) ||
   (theta < -Math.PI/4 && theta > -3*Math.PI / 4)) {
    dBox = sqr.getS() / (2*Math.sin(theta));
} else {
    dBox = sqr.getS() / (2*Math.cos(theta));
}
boolean touching = (Math.abs(dBox) >=
                    Math.sqrt(Math.pow(sqr.getX()-cir.getX(), 2) +
                              Math.pow(sqr.getY()-cir.getY(), 2)));

tsc is not recognized as internal or external command

You have missed typescript installation, just run below command and then try tsc --init

npm install -g typescript

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

Javascript to open popup window and disable parent window

This is how I finally did it! You can put a layer (full sized) over your body with high z-index and, of course hidden. You will make it visible when the window is open, make it focused on click over parent window (the layer), and finally will disappear it when the opened window is closed or submitted or whatever.

      .layer
  {
        position: fixed;
        opacity: 0.7;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        z-index: 999999;
        background-color: #BEBEBE;
        display: none;
        cursor: not-allowed;
  }

and layer in the body:

                <div class="layout" id="layout"></div>

function that opens the popup window:

    var new_window;
    function winOpen(){
        $(".layer").show();
        new_window=window.open(srcurl,'','height=750,width=700,left=300,top=200');
    }

keeping new window focused:

         $(document).ready(function(){
             $(".layout").click(function(e) {
                new_window.focus();
            }
        });

and in the opened window:

    function submit(){
        var doc = window.opener.document,
        doc.getElementById("layer").style.display="none";
         window.close();
    }   

   window.onbeforeunload = function(){
        var doc = window.opener.document;
        doc.getElementById("layout").style.display="none";
   }

I hope it would help :-)

CSS horizontal scroll

Here's a solution with flexbox for images with variable width and height:

.container {
  display: flex;
  flex-wrap: no-wrap;
  overflow-x: auto;
  margin: 20px;
}
img {
  flex: 0 0 auto;
  width: auto;
  height: 100px;
  max-width: 100%;
  margin-right: 10px;
}

Example: JsFiddle

How to check if X server is running?

You can use xdpyinfo (can be installed via apt-get install x11-utils).

Extending the User model with custom fields in Django

Simple and effective approach is models.py

from django.contrib.auth.models import User
class CustomUser(User):
     profile_pic = models.ImageField(upload_to='...')
     other_field = models.CharField()

JS: iterating over result of getElementsByClassName using Array.forEach

Is the result of getElementsByClassName an Array?

No

If not, what is it?

As with all DOM methods that return multiple elements, it is a NodeList, see https://developer.mozilla.org/en/DOM/document.getElementsByClassName

How to check whether Kafka Server is running?

The good option is to use AdminClient as below before starting to produce or consume the messages

private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;           
 try (AdminClient client = AdminClient.create(properties)) {
            client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
        } catch (ExecutionException ex) {
            LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
            return;
        }

Build Step Progress Bar (css and jquery)

There are a lot of very nice answers on this page and I googled for some more, but none of the answers ticked all the checkboxes on my wish list:

  • CSS only, no Javascript
  • Stick to Tom Kenny's Best Design Practices
  • Layout like the other answers
  • Each step has a name and a number
  • Responsive layout: font size independent
  • Fluid layout: the list and its items scale with the available width
  • The names and numbers are centered in their block
  • The "done" color goes up to and including the active item, but not past it.
  • The active item should stand out graphically

So I mixed the code of several examples, fixed the things that I needed and here is the result:

Progress Tracker v2

I used the following CSS and HTML:

_x000D_
_x000D_
/* Progress Tracker v2 */_x000D_
ol.progress[data-steps="2"] li { width: 49%; }_x000D_
ol.progress[data-steps="3"] li { width: 33%; }_x000D_
ol.progress[data-steps="4"] li { width: 24%; }_x000D_
ol.progress[data-steps="5"] li { width: 19%; }_x000D_
ol.progress[data-steps="6"] li { width: 16%; }_x000D_
ol.progress[data-steps="7"] li { width: 14%; }_x000D_
ol.progress[data-steps="8"] li { width: 12%; }_x000D_
ol.progress[data-steps="9"] li { width: 11%; }_x000D_
_x000D_
.progress {_x000D_
    width: 100%;_x000D_
    list-style: none;_x000D_
    list-style-image: none;_x000D_
    margin: 20px 0 20px 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
.progress li {_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.progress .name {_x000D_
    display: block;_x000D_
    vertical-align: bottom;_x000D_
    text-align: center;_x000D_
    margin-bottom: 1em;_x000D_
    color: black;_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .step {_x000D_
    color: black;_x000D_
    border: 3px solid silver;_x000D_
    background-color: silver;_x000D_
    border-radius: 50%;_x000D_
    line-height: 1.2;_x000D_
    width: 1.2em;_x000D_
    height: 1.2em;_x000D_
    display: inline-block;_x000D_
    z-index: 0;_x000D_
}_x000D_
_x000D_
.progress .step span {_x000D_
    opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .active .name,_x000D_
.progress .active .step span {_x000D_
    opacity: 1;_x000D_
}_x000D_
_x000D_
.progress .step:before {_x000D_
    content: "";_x000D_
    display: block;_x000D_
    background-color: silver;_x000D_
    height: 0.4em;_x000D_
    width: 50%;_x000D_
    position: absolute;_x000D_
    bottom: 0.6em;_x000D_
    left: 0;_x000D_
    z-index: -1;_x000D_
}_x000D_
_x000D_
.progress .step:after {_x000D_
    content: "";_x000D_
    display: block;_x000D_
    background-color: silver;_x000D_
    height: 0.4em;_x000D_
    width: 50%;_x000D_
    position: absolute;_x000D_
    bottom: 0.6em;_x000D_
    right: 0;_x000D_
    z-index: -1;_x000D_
}_x000D_
_x000D_
.progress li:first-of-type .step:before {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
.progress li:last-of-type .step:after {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .done .step:before,_x000D_
.progress .done .step:after,_x000D_
.progress .active .step,_x000D_
.progress .active .step:before {_x000D_
    background-color: yellowgreen;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .active .step {_x000D_
    border: 3px solid yellowgreen;_x000D_
}
_x000D_
<!-- Progress Tracker v2 -->_x000D_
<ol class="progress" data-steps="4">_x000D_
    <li class="done">_x000D_
        <span class="name">Foo</span>_x000D_
        <span class="step"><span>1</span></span>_x000D_
    </li>_x000D_
    <li class="done">_x000D_
        <span class="name">Bar</span>_x000D_
        <span class="step"><span>2</span></span>_x000D_
    </li>_x000D_
    <li class="active">_x000D_
        <span class="name">Baz</span>_x000D_
        <span class="step"><span>3</span></span>_x000D_
    </li>_x000D_
    <li>_x000D_
        <span class="name">Quux</span>_x000D_
        <span class="step"><span>4</span></span>_x000D_
    </li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

As can be seen in the example above, there are now two list item classes to take note of: active and done. Use class="active" for the current step, use class="done" for all steps before it.

Also note the data-steps="4" in the ol tag; set this to the total number of steps to apply the correct size to all list items.

Feel free to play around with the JSFiddle. Enjoy!

OAuth: how to test with local URLs?

I found xip.io which automatically converts a fixed url to a embedded localhost domain.

For example lets say your localhost server is running on 127.0.0.1:8000 You can go to http://www.127.0.0.1.xip.io:5555/ to access this server. You can then add this address to Oauth configuration for Facebook or Google.

Is there a JavaScript / jQuery DOM change listener?

Many sites use AJAX/XHR/fetch to add, show, modify content dynamically and window.history API instead of in-site navigation so current URL is changed programmatically. Such sites are called SPA, short for Single Page Application.


Usual JS methods of detecting page changes

  • MutationObserver (docs) to literally detect DOM changes:

  • Event listener for sites that signal content change by sending a DOM event:

  • Periodic checking of DOM via setInterval:
    Obviously this will work only in cases when you wait for a specific element identified by its id/selector to appear, and it won't let you universally detect new dynamically added content unless you invent some kind of fingerprinting the existing contents.

  • Cloaking History API:

    let _pushState = History.prototype.pushState;
    History.prototype.pushState = function (state, title, url) {
      _pushState.call(this, state, title, url);
      console.log('URL changed', url)
    };
    
  • Listening to hashchange, popstate events:

    window.addEventListener('hashchange', e => {
      console.log('URL hash changed', e);
      doSomething();
    });
    window.addEventListener('popstate', e => {
      console.log('State changed', e);
      doSomething();
    });
    


Extensions-specific methods

All above-mentioned methods can be used in a content script. Note that content scripts aren't automatically executed by the browser in case of programmatic navigation via window.history in the web page because only the URL was changed but the page itself remained the same (the content scripts run automatically only once in page lifetime).

Now let's look at the background script.

Detect URL changes in a background / event page.

There are advanced API to work with navigation: webNavigation, webRequest, but we'll use simple chrome.tabs.onUpdated event listener that sends a message to the content script:

  • manifest.json:
    declare background/event page
    declare content script
    add "tabs" permission.

  • background.js

    var rxLookfor = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
    chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
      if (rxLookfor.test(changeInfo.url)) {
        chrome.tabs.sendMessage(tabId, 'url-update');
      }
    });
    
  • content.js

    chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
      if (msg === 'url-update') {
        // doSomething();
      }
    });
    

Python return statement error " 'return' outside function"

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

C# Error: Parent does not contain a constructor that takes 0 arguments

The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:

public class child : parent {
    public child(int i) : base(i) {
        Console.WriteLine("child");
    }
}

Export specific rows from a PostgreSQL table as INSERT SQL script

I tried to write a procedure doing that, based on @PhilHibbs codes, on a different way. Please have a look and test.

 CREATE OR REPLACE FUNCTION dump(IN p_schema text, IN p_table text, IN p_where text)
   RETURNS setof text AS
 $BODY$
 DECLARE
     dumpquery_0 text;
     dumpquery_1 text;
     selquery text;
     selvalue text;
     valrec record;
     colrec record;
 BEGIN

     -- ------ --
     -- GLOBAL --
     --   build base INSERT
     --   build SELECT array[ ... ]
     dumpquery_0 := 'INSERT INTO ' ||  quote_ident(p_schema) || '.' || quote_ident(p_table) || '(';
     selquery    := 'SELECT array[';

     <<label0>>
     FOR colrec IN SELECT table_schema, table_name, column_name, data_type
                   FROM information_schema.columns
                   WHERE table_name = p_table and table_schema = p_schema
                   ORDER BY ordinal_position
     LOOP
         dumpquery_0 := dumpquery_0 || quote_ident(colrec.column_name) || ',';
         selquery    := selquery    || 'CAST(' || quote_ident(colrec.column_name) || ' AS TEXT),';
     END LOOP label0;

     dumpquery_0 := substring(dumpquery_0 ,1,length(dumpquery_0)-1) || ')';
     dumpquery_0 := dumpquery_0 || ' VALUES (';
     selquery    := substring(selquery    ,1,length(selquery)-1)    || '] AS MYARRAY';
     selquery    := selquery    || ' FROM ' ||quote_ident(p_schema)||'.'||quote_ident(p_table);
     selquery    := selquery    || ' WHERE '||p_where;
     -- GLOBAL --
     -- ------ --

     -- ----------- --
     -- SELECT LOOP --
     --   execute SELECT built and loop on each row
     <<label1>>
     FOR valrec IN  EXECUTE  selquery
     LOOP
         dumpquery_1 := '';
         IF not found THEN
             EXIT ;
         END IF;

         -- ----------- --
         -- LOOP ARRAY (EACH FIELDS) --
         <<label2>>
         FOREACH selvalue in ARRAY valrec.MYARRAY
         LOOP
             IF selvalue IS NULL
             THEN selvalue := 'NULL';
             ELSE selvalue := quote_literal(selvalue);
             END IF;
             dumpquery_1 := dumpquery_1 || selvalue || ',';
         END LOOP label2;
         dumpquery_1 := substring(dumpquery_1 ,1,length(dumpquery_1)-1) || ');';
         -- LOOP ARRAY (EACH FIELD) --
         -- ----------- --

         -- debug: RETURN NEXT dumpquery_0 || dumpquery_1 || ' --' || selquery;
         -- debug: RETURN NEXT selquery;
         RETURN NEXT dumpquery_0 || dumpquery_1;

     END LOOP label1 ;
     -- SELECT LOOP --
     -- ----------- --

 RETURN ;
 END
 $BODY$
   LANGUAGE plpgsql VOLATILE;

And then :

-- for a range
SELECT dump('public', 'my_table','my_id between 123456 and 123459'); 
-- for the entire table
SELECT dump('public', 'my_table','true');

tested on my postgres 9.1, with a table with mixed field datatype (text, double, int,timestamp without time zone, etc).

That's why the CAST in TEXT type is needed. My test run correctly for about 9M lines, looks like it fail just before 18 minutes of running.

ps : I found an equivalent for mysql on the WEB.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

I had the error after trying to select a subset of rows:

df = df.reindex(index=my_index)

Turns out that my_index contained values that were not contained in df.index, so the reindex function inserted some new rows and filled them with nan.

batch file to copy files to another location?

Open Notepad.

Type the following lines into it (obviously replace the folders with your ones)

@echo off
rem you could also remove the line above, because it might help you to see what happens

rem /i option is needed to avoid the batch file asking you whether destination folder is a file or a folder
rem /e option is needed to copy also all folders and subfolders
xcopy "c:\New Folder" "c:\Copy of New Folder" /i /e

Save the file as backup.bat (not .txt)

Double click on the file to run it. It will backup the folder and all its contents files/subfolders.

Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.

To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.

Checking if an object is a given type in Swift

If you only want to know if an object is a subtype of a given type then there is a simpler approach:

class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}

func area (shape: Shape) -> Double {
  if shape is Circle { ... }
  else if shape is Rectangle { ... }
}

“Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

In the above the phrase 'of a certain subclass type' is important. The use of is Circle and is Rectangle is accepted by the compiler because that value shape is declared as Shape (a superclass of Circle and Rectangle).

If you are using primitive types, the superclass would be Any. Here is an example:

 21> func test (obj:Any) -> String {
 22.     if obj is Int { return "Int" }
 23.     else if obj is String { return "String" }
 24.     else { return "Any" }
 25. } 
 ...  
 30> test (1)
$R16: String = "Int"
 31> test ("abc")
$R17: String = "String"
 32> test (nil)
$R18: String = "Any"

How to run function in AngularJS controller on document ready?

Angular has several timepoints to start executing functions. If you seek for something like jQuery's

$(document).ready();

You may find this analog in angular to be very useful:

$scope.$watch('$viewContentLoaded', function(){
    //do something
});

This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.

UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:

$scope.$watch('$viewContentLoaded', 
    function() { 
        $timeout(function() {
            //do something
        },0);    
});

JQuery select2 set default value from an option in list?

Don't know others issue, Only this code worked for me.

$('select').val('').select2();

Toggle display:none style with JavaScript

Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul to hide by scrolling up or fading away using CSS transition, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.

Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/

HTML:

<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>

CSS:

#subforms {
    overflow-x: visible; 
    overflow-y: visible;
}

.hide {
    display: none; 
}

Script:

document.getElementById( 'showTags' ).addEventListener( 'click', function () {
    document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );

Element.prototype.toggleClass = function ( className ) {
    if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
        this.className = ( this.className + ' ' + className ).trim();
    } else {
        this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
    };
};

ModuleNotFoundError: No module named 'sklearn'

I did the following:

import sys
!{sys.executable} -m pip install sklearn

What's the best UML diagramming tool?

I strongly recommend BOUML. It's a free UML modelling application, which:

  • is extremely fast (fastest UML tool ever created, check out benchmarks),
  • has rock solid C++, Java, PHP and others import support,
  • is multiplatform (Linux, Windows, other OSes),
  • has a great SVG export support, which is important, because viewing large graphs in vector format, which scales fast in e.g. Firefox, is very convenient (you can quickly switch between "birds eye" view and class detail view),
  • is full featured, impressively intensively developed (look at development history, it's hard to believe that such fast progress is possible).
  • supports plugins, has modular architecture (this allows user contributions, looks like BOUML community is forming up)

Believe me, there is no better tool. StarUML is a retarded turtle compared to BOUML. ArgoUML simply doesn't work. Dia is a ergonomy^-1 software.

JAVA How to remove trailing zeros from a double

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));

System.Runtime.InteropServices.COMException (0x800A03EC)

For all of those, who still experiencing this problem, I just spent 2 days tracking down the bloody thing. I was getting the same error when there was no rows in dataset. Seems obvious, but error message is very obscure, hence 2 days.

How to slice an array in Bash

See the Parameter Expansion section in the Bash man page. A[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 1.

A=( foo bar "a  b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}")       # slice to the end of the array
echo "${B[@]}"        # bar a  b c
echo "${B[1]}"        # a  b c
echo "${C[@]}"        # bar a  b c 42
echo "${C[@]: -2:2}"  # a  b c 42 # The space before the - is necesssary

Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.

Cross browser method to fit a child div to its parent's width

If you put position:relative; on the outer element, the inner element will place itself according to this one. Then a width:auto; on the inner element will be the same as the width of the outer.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

You need to load jquery first before bootstrap.

require.config({
    paths: {
        jquery: 'libs/jquery/jquery',
        underscore: 'libs/underscore/underscore',
        backbone: 'libs/backbone/backbone',
        bootstrap: 'libs/bootstrap',
        jquerytablesorter: 'libs/tablesorter/jquery.tablesorter',
        tablesorter: 'libs/tablesorter/tables',
        ajaxupload: 'libs/ajax-upload',
        templates: '../templates'
    },
    shim: {
        'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        },
        'jquery': {
            exports: '$'
        },
        'bootstrap': {
            deps: ['jquery'],
            exports: '$'
        },
        'jquerytablesorter': {
            deps: ['jquery'],
            exports: '$'
        },
        'tablesorter': {
            deps: ['jquery'],
            exports: '$'
        },
        'ajaxupload': {
            deps: ['jquery'],
            exports: '$'
        },
        'underscore': {
            exports: '_'
        },
    }
});
require(['app', ], function(App) {
    App.initialize();
});

Works like charm! quick and easy fix.

Can I make 'git diff' only the line numbers AND changed file names?

I know this is an old question but on Windows, this filters the git output to the files and changed line numbers:

(git diff -p --stat) | findstr "@@ --git"

diff --git a/dir1/dir2/file.cpp b/dir1/dir2/file.cpp
@@ -47,6 +47,7 @@ <some function name>
@@ -97,7 +98,7 @@ <another functon name>

To extract the files and the changed lines from that is a bit more work:

for /f "tokens=3,4* delims=-+ " %f in ('^(git diff -p --stat .^) ^| findstr ^"@@ --git^"') do @echo %f

a/dir1/dir2/file.cpp
47,7
98,7

Git - remote: Repository not found

If you are on windows got to control pannel -> windows Credentials then remove github credential from generic credential option. Then try to clone

Read JSON data in a shell script

Similarly using Bash regexp. Shall be able to snatch any key/value pair.

key="Body"
re="\"($key)\": \"([^\"]*)\""

while read -r l; do
    if [[ $l =~ $re ]]; then
        name="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]}"
        echo "$name=$value"
    else
        echo "No match"
    fi
done

Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded ". This is an illustration. Better to use some "industrial" parser :)

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

<input type="text" id="firstname" placeholder="First Name"

Note: You can change the placeholder, id and type value to "email" or whatever suits your need.

More details by W3Schools at:http://www.w3schools.com/tags/att_input_placeholder.asp

But by far the best solutions are by Floern and Vivek Mhatre ( edited by j0k )

VBA (Excel) Initialize Entire Array without Looping

I want to initialize every single element of the array to some initial value. So if I have an array Dim myArray(300) As Integer of 300 integers, for example, all 300 elements would hold the same initial value (say, the number 13).

Can anyone explain how to do this, without looping? I'd like to do it in one statement if possible.

What do I win?

Sub SuperTest()
   Dim myArray
   myArray = Application.Transpose([index(Row(1:300),)-index(Row(1:300),)+13])
End Sub

How to check if there exists a process with a given pid in Python?

This will work for Linux, for example if you want to check if banshee is running... (banshee is a music player)

import subprocess

def running_process(process):
    "check if process is running. < process > is the name of the process."

    proc = subprocess.Popen(["if pgrep " + process + " >/dev/null 2>&1; then echo 'True'; else echo 'False'; fi"], stdout=subprocess.PIPE, shell=True)

    (Process_Existance, err) = proc.communicate()
    return Process_Existance

# use the function
print running_process("banshee")

Can you blur the content beneath/behind a div?

If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before

//HTML

<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
    <div class="morph-button morph-button-overlay morph-button-fixed">
        <button id="user-interface" type="button">MORE INFO</button>
        <!--a id="user-interface" href="javascript:void(0)">popup</a-->
        <div class="morph-content">
            <div>
                <div class="content-style-overlay">
                    <span class="icon icon-close">Close the overlay</span>
                    <h2>About Parsley</h2>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                    <p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
                    <p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
                </div>
            </div>
        </div>
    </div>
</div>

//CSS

/* Blur - doesn't work on IE */

.blur-on, .blur-element {
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    filter: blur(10px);

    -webkit-transition: all 5s linear;
    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}
.blur-off {
    -webkit-filter: blur(0px) !important;
    -moz-filter   : blur(0px) !important;
    -o-filter     : blur(0px) !important;
    -ms-filter    : blur(0px) !important;
    filter        : blur(0px) !important;
}
.blur-bgimage:before {
    content: "";
    position: absolute;
    height: 20%; width: 20%;
    background-size: cover;
    background: inherit;
    z-index: -1;

    transform: scale(5);
    transform-origin: top left;
    filter: blur(2px);       
    -moz-transform: scale(5);
    -moz-transform-origin: top left;
    -moz-filter: blur(2px);       
    -webkit-transform: scale(5);
    -webkit-transform-origin: top left;
    -webkit-filter: blur(2px);
    -o-transform: scale(5);
    -o-transform-origin: top left;
    -o-filter: blur(2px);       

    transition        : all 5s linear;
    -moz-transition   : all 5s linear;
    -webkit-transition: all 5s linear;
    -o-transition     : all 5s linear;
}


//Javascript

function blurBehindPopup() {
    if(blurredElements.length == 0) {
        for(var i=0; i < document.body.children.length; i++) {
            var element = document.body.children[i];
            if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
                classie.addClass( element, 'blur-element' );
                blurredElements.push(element);
            }
        }
    } else {
        for(var i=0; i < blurredElements.length; i++) {
            classie.addClass( blurredElements[i], 'blur-element' );
        }
    }
}
function unblurBehindPopup() {
    for(var i=0; i < blurredElements.length; i++) {
        classie.removeClass( blurredElements[i], 'blur-element' );
    }
}

Full Working Example Link

Compute elapsed time

var StopWatch = function (performance) {
    this.startTime = 0;
    this.stopTime = 0;
    this.running = false;
    this.performance = performance === false ? false : !!window.performance;
};

StopWatch.prototype.currentTime = function () {
    return this.performance ? window.performance.now() : new Date().getTime();
};

StopWatch.prototype.start = function () {
    this.startTime = this.currentTime();
    this.running = true;
};

StopWatch.prototype.stop = function () {
    this.stopTime = this.currentTime();
    this.running = false;
};

StopWatch.prototype.getElapsedMilliseconds = function () {
    if (this.running) {
        this.stopTime = this.currentTime();
    }

    return this.stopTime - this.startTime;
};

StopWatch.prototype.getElapsedSeconds = function () {
    return this.getElapsedMilliseconds() / 1000;
};

StopWatch.prototype.printElapsed = function (name) {
    var currentName = name || 'Elapsed:';

    console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};

Benchmark

var stopwatch = new StopWatch();
stopwatch.start();

for (var index = 0; index < 100; index++) {
    stopwatch.printElapsed('Instance[' + index + ']');
}

stopwatch.stop();

stopwatch.printElapsed();

Output

Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]

performance.now() is optional - just pass false into StopWatch constructor function.

How to find a value in an array and remove it by using PHP array functions?

First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-

<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>

Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-

<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>

Hope it helps.

How to manage exceptions thrown in filters in Spring?

So this is what I did:

I read the basics about filters here and I figured out that I need to create a custom filter that will be first in the filter chain and will have a try catch to catch all runtime exceptions that might occur there. Then i need to create the json manually and put it in the response.

So here is my custom filter:

public class ExceptionHandlerFilter extends OncePerRequestFilter {

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (RuntimeException e) {

            // custom error response class used across my project
            ErrorResponse errorResponse = new ErrorResponse(e);

            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.getWriter().write(convertObjectToJson(errorResponse));
    }
}

    public String convertObjectToJson(Object object) throws JsonProcessingException {
        if (object == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }
}

And then i added it in the web.xml before the CorsFilter. And it works!

<filter> 
    <filter-name>exceptionHandlerFilter</filter-name> 
    <filter-class>xx.xxxxxx.xxxxx.api.controllers.filters.ExceptionHandlerFilter</filter-class> 
</filter> 


<filter-mapping> 
    <filter-name>exceptionHandlerFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

<filter> 
    <filter-name>CorsFilter</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 

<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

Singleton in Android

The most clean and modern way to use singletons in Android is just to use the Dependency Injection framework called Dagger 2. Here you have an explanation of possible scopes you can use. Singleton is one of these scopes. Dependency Injection is not that easy but you shall invest a bit of your time to understand it. It also makes testing easier.

Object not found! The requested URL was not found on this server. localhost

Simply my project wasn't in htdocs thats why it was showing me an this error make sure you put your project in HTdocs not in directory inside it

Android Fastboot devices not returning device

If you got nothing when inputted fastboot devices, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-'). Then you can see you devices via fastboot devices and continue to flash your devices.

note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

just add

 <dependency>
      <groupId>com.microsoft.sqlserver</groupId>
      <artifactId>sqljdbc4</artifactId>
      <version>4.0</version>
      <scope>runtime</scope>
 </dependency>

Repeating a function every few seconds

Use a timer. There are 3 basic kinds, each suited for different purposes.

Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.

When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.

This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.

For most cases, I recommend System.Timers.Timer.

How to find current transaction level?

Run this:

SELECT CASE transaction_isolation_level 
WHEN 0 THEN 'Unspecified' 
WHEN 1 THEN 'ReadUncommitted' 
WHEN 2 THEN 'ReadCommitted' 
WHEN 3 THEN 'Repeatable' 
WHEN 4 THEN 'Serializable' 
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL 
FROM sys.dm_exec_sessions 
where session_id = @@SPID

docs.microsoft.com reference for the constant values.

How to push local changes to a remote git repository on bitbucket

Use git push origin master instead.

You have a repository locally and the initial git push is "pushing" to it. It's not necessary to do so (as it is local) and it shows everything as up-to-date. git push origin master specifies a a remote repository (origin) and the branch located there (master).

For more information, check out this resource.

Validation of radio button group using jQuery validation plugin

Another way to validate is like this.

var $radio = $('input:radio[name="nameRadioButton"]');
$radio.addClass("validate[required]");

I hope my example will help you

Set selected option of select box

I had a problem where the value was not set because of a syntax error before the call.

$("#someId").value(33); //script bailed here without showing any errors Note: .value instead of .val
$("#gate").val('Gateway 2'); //this line didn't work.

Check for syntax errors before the call.

Finish all activities at a time

You can try just finishAffinity() , its close all current activities to works on above v4.1

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

How to save a plot into a PDF file without a large margin around

The function export_fig on the MATLAB file exchange will crop the whitespace around an output PDF/EPS file by default when it exports a figure.

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.

Remember: we're not instantiating the Console class, String class, Array Class.

class Book
{
    public static int myInt = 0;
}

public class Exercise
{
    static void Main()
    {
        Book book = new Book();
       //Use the class name directly to call the property myInt, 
      //don't use the object to access the value of property myInt

        Console.WriteLine(Book.myInt);

        Console.ReadKey();

    }
}

How to find the files that are created in the last hour in unix

Check out this link for more details.

To find files which are created in last one hour in current directory, you can use -amin

find . -amin -60 -type f

This will find files which are created with in last 1 hour.

How to check python anaconda version installed on Windows 10 PC?

If you want to check the python version in a particular cond environment you can also use conda list python

Android: how do I check if activity is running?

I have used task.topActivity instead of task.baseActivity and it works fine for me.

   protected Boolean isNotificationActivityRunning() {
    ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (ActivityManager.RunningTaskInfo task : tasks) {
        if (task.topActivity.getClassName().equals(NotificationsActivity.class.getCanonicalName()))
            return true;
    }

    return false;
}

Handling ExecuteScalar() when no results are returned

SQL NULL value

  • equivalent in C# is DBNull.Value
  • if a NULLABLE column has no value, this is what is returned
  • comparison in SQL: IF ( value IS NULL )
  • comparison in C#: if (obj == DBNull.Value)
  • visually represented in C# Quick-Watch as {}

Best practice when reading from a data reader:

var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());

In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be

select MAX(ID) from <table name> where <impossible condition>

The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)

var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));

jQuery: Slide left and slide right

You can always just use jQuery to add a class, .addClass or .toggleClass. Then you can keep all your styles in your CSS and out of your scripts.

http://jsfiddle.net/B8L3x/1/

How to parse a month name (string) to an integer for comparison in C#?

I translate it into C# code in Spanish version, regards:

public string ObtenerNumeroMes(string NombreMes){

       string NumeroMes;   

       switch(NombreMes) {

        case ("ENERO") :
            NumeroMes = "01";
            return NumeroMes;

        case ("FEBRERO") :
            NumeroMes = "02";
            return NumeroMes;

        case ("MARZO") :
            NumeroMes = "03";
            return NumeroMes;

        case ("ABRIL") :
            NumeroMes = "04";
            return NumeroMes;

        case ("MAYO") :
            NumeroMes = "05";
            return NumeroMes;

        case ("JUNIO") :
            NumeroMes = "06";
            return NumeroMes;

        case ("JULIO") :
            NumeroMes = "07";
            return NumeroMes;

        case ("AGOSTO") :
            NumeroMes = "08";
            return NumeroMes;

        case ("SEPTIEMBRE") :
            NumeroMes = "09";
            return NumeroMes;

        case ("OCTUBRE") :
            NumeroMes = "10";
            return NumeroMes;

        case ("NOVIEMBRE") :
            NumeroMes = "11";
            return NumeroMes;

        case ("DICIEMBRE") :
            NumeroMes = "12";
            return NumeroMes;

            default:
            Console.WriteLine("Error");
            return "ERROR";

        }

   }

How do I return the SQL data types from my query?

There MUST be en easier way to do this... Low and behold, there is...!

"sp_describe_first_result_set" is your friend!

Now I do realise the question was asked specifically for SQL Server 2000, but I was looking for a similar solution for later versions and discovered some native support in SQL to achieve this.

In SQL Server 2012 onwards cf. "sp_describe_first_result_set" - Link to BOL

I had already implemented a solution using a technique similar to @Trisped's above and ripped it out to implement the native SQL Server implementation.

In case you're not on SQL Server 2012 or Azure SQL Database yet, here's the stored proc I created for pre-2012 era databases:

CREATE PROCEDURE [fn].[GetQueryResultMetadata] 
    @queryText VARCHAR(MAX)
AS
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    --SET NOCOUNT ON;

    PRINT @queryText;

    DECLARE
                @sqlToExec NVARCHAR(MAX) = 
                    'SELECT TOP 1 * INTO #QueryMetadata FROM ('
                    +
                    @queryText
                    +
                    ') T;'
                    + '
                        SELECT
                                    C.Name                          [ColumnName],
                                    TP.Name                         [ColumnType],
                                    C.max_length                    [MaxLength],
                                    C.[precision]                   [Precision],
                                    C.[scale]                       [Scale],
                                    C.[is_nullable]                 IsNullable
                        FROM
                                    tempdb.sys.columns              C
                                        INNER JOIN
                                    tempdb.sys.types                TP
                                                                                ON
                                                                                        TP.system_type_id = C.system_type_id
                                                                                            AND
                                                                                        -- exclude custom types
                                                                                        TP.system_type_id = TP.user_type_id
                        WHERE
                                    [object_id] = OBJECT_ID(N''tempdb..#QueryMetadata'');
            '

    EXEC sp_executesql @sqlToExec

END

Jenkins - how to build a specific branch

This is extension of answer provided by Ranjith

I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter

And after that, you can specify branches to build. Branch to Build

Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"

You can also write a groovy script to fetch all your branches to in active choice parameter.

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

Memory errors and list limits?

First off, see How Big can a Python Array Get? and Numpy, problem with long arrays

Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:

  1. If you are running on an older OS or one that forces processes to use a limited amount of memory, you may need to increase the amount of memory the Python process has access to.
  2. Break the list apart using chunking. For example, do the first 1000 elements of the list, pickle and save them to disk, and then do the next 1000. To work with them, unpickle one chunk at a time so that you don't run out of memory. This is essentially the same technique that databases use to work with more data than will fit in RAM.

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

asp.net Button OnClick event not firing

Try to Clean your solution and then try once again.

It will definitely work. Because every thing in code seems to be ok.

Go through this link for cleaning solution>

http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/

How to color the Git console?

For example see https://web.archive.org/web/20080506194329/http://www.arthurkoziel.com/2008/05/02/git-configuration/

The interesting part is

Colorized output:

git config --global color.branch auto
git config --global color.diff auto
git config --global color.interactive auto
git config --global color.status auto

Delete an element from a dictionary

The del statement is what you're looking for. If you have a dictionary named foo with a key called 'bar', you can delete 'bar' from foo like this:

del foo['bar']

Note that this permanently modifies the dictionary being operated on. If you want to keep the original dictionary, you'll have to create a copy beforehand:

>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}

The dict call makes a shallow copy. If you want a deep copy, use copy.deepcopy.

Here's a method you can copy & paste, for your convenience:

def minus_key(key, dictionary):
    shallow_copy = dict(dictionary)
    del shallow_copy[key]
    return shallow_copy

How can you strip non-ASCII characters from a string? (in C#)

I used this regex expression:

    string s = "søme string";
    Regex regex = new Regex(@"[^a-zA-Z0-9\s]", (RegexOptions)0);
    return regex.Replace(s, "");

Deny direct access to all .php files except index.php

An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.

How can I change the default width of a Twitter Bootstrap modal box?

Altering the class model-dialog you can achieve expected result. These small tricks work for me. Hope it will help you to solve this issue.

.modal-dialog {
    width: 70%;
}

Mock a constructor with parameter

To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:

Pattern 1 - using one-line methods for object creation

To use pattern 1 (testing a class called MyClass), you would replace a call like

   Foo foo = new Foo( a, b, c );

with

   Foo foo = makeFoo( a, b, c );

and write a one-line method

   Foo makeFoo( A a, B b, C c ) { 
        return new Foo( a, b, c );
   }

It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.

When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.

Your test class might contain members like

  @Mock private Foo mockFoo;
  private MyClass toTest = spy(new MyClass());

Lastly, inside your test method you mock out the call to makeFoo with a line like

  doReturn( mockFoo )
      .when( toTest )
      .makeFoo( any( A.class ), any( B.class ), any( C.class ));

You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.

If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:

http://code.google.com/p/mockito/wiki/MockingObjectCreation

Difference Between Select and SelectMany

Some SelectMany may not be necessary. Below 2 queries give the same result.

Customers.Where(c=>c.Name=="Tom").SelectMany(c=>c.Orders)

Orders.Where(o=>o.Customer.Name=="Tom")

For 1-to-Many relationship,

  1. if Start from "1", SelectMany is needed, it flattens the many.
  2. if Start from "Many", SelectMany is not needed. (still be able to filter from "1", also this is simpler than below standard join query)

from o in Orders
join c in Customers on o.CustomerID equals c.ID
where c.Name == "Tom"
select o

How to pass List from Controller to View in MVC 3

  1. Create a model which contains your list and other things you need for the view.

    For example:

    public class MyModel
    {
        public List<string> _MyList { get; set; }
    }
    
  2. From the action method put your desired list to the Model, _MyList property, like:

    public ActionResult ArticleList(MyModel model)
    {
        model._MyList = new List<string>{"item1","item2","item3"};
        return PartialView(@"~/Views/Home/MyView.cshtml", model);
    }
    
  3. In your view access the model as follows

    @model MyModel
    foreach (var item in Model)
    {
       <div>@item</div>
    }
    

I think it will help for start.

Can't bind to 'ngModel' since it isn't a known property of 'input'

I'm using Angular 5.

In my case, I needed to import ReactiveFormsModule too.

File app.module.ts (or anymodule.module.ts):

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ],

How to grep (search) committed code in the Git history

My favorite way to do it is with git log's -G option (added in version 1.7.4).

-G<regex>
       Look for differences whose added or removed line matches the given <regex>.

There is a subtle difference between the way the -G and -S options determine if a commit matches:

  • The -S option essentially counts the number of times your search matches in a file before and after a commit. The commit is shown in the log if the before and after counts are different. This will not, for example, show commits where a line matching your search was moved.
  • With the -G option, the commit is shown in the log if your search matches any line that was added, removed, or changed.

Take this commit as an example:

diff --git a/test b/test
index dddc242..60a8ba6 100644
--- a/test
+++ b/test
@@ -1 +1 @@
-hello hello
+hello goodbye hello

Because the number of times "hello" appears in the file is the same before and after this commit, it will not match using -Shello. However, since there was a change to a line matching hello, the commit will be shown using -Ghello.

GDB: break if variable equal value

First, you need to compile your code with appropriate flags, enabling debug into code.

$ gcc -Wall -g -ggdb -o ex1 ex1.c

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }

break on lines 5 and looks if i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i

checking breakpoints

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5

running the program

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)

Bootstrap: Open Another Modal in Modal

I also had some trouble with my scrollable modals, so I did something like this:

  $('.modal').on('shown.bs.modal', function () {
    $('body').addClass('modal-open');
    // BS adds some padding-right to acomodate the scrollbar at right
    $('body').removeAttr('style');
  })

  $(".modal [data-toggle='modal']").click(function(){
    $(this).closest(".modal").modal('hide');
  });

It will serve for any modal whithin a modal that comes to appear. Note that the first its closed so the second can appear. No changes in the Bootstrap structure.

How do I configure different environments in Angular.js?

One cool solution might be separating all environment-specific values into some separate angular module, that all other modules depend on:

angular.module('configuration', [])
       .constant('API_END_POINT','123456')
       .constant('HOST','localhost');

Then your modules that need those entries can declare a dependency on it:

angular.module('services',['configuration'])
       .factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
           return $resource(API_END_POINT + 'user');
       });

Now you could think about further cool stuff:

The module, that contains the configuration can be separated into configuration.js, that will be included at your page.

This script can be easily edited by each of you, as long as you don’t check this separate file into git. But it's easier to not check in the configuration if it is in a separate file. Also, you could branch it locally.

Now, if you have a build-system, like ANT or Maven, your further steps could be implementing some placeholders for the values API_END_POINT, that will be replaced during build-time, with your specific values.

Or you have your configuration_a.js and configuration_b.js and decide at the backend which to include.

jquery.ajax Access-Control-Allow-Origin

http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

refer the above link for more details on Cross domain resource sharing.

you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

sample below:

ajax call:

$(document).ready(function () {
        $.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "<your middle man service url here>/GetQuote?callback=?",
            data: { symbol: 'ctsh' },
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'
        });
    });

service (asmx) which will return jsonp:

[WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void GetQuote(String symbol,string callback)
    {          

        WebProxy myProxy = new WebProxy("<proxy url here>", true);

        myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
        StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
        SQ.Proxy = myProxy;
        String result = SQ.GetQuote(symbol);
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(result));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();         
    }

jQuery fade out then fade in

fade the other in in the callback of fadeout, which runs when fadeout is done. Using your code:

$('#two, #three').hide();
$('.slide').click(function(){
    var $this = $(this);
    $this.fadeOut(function(){ $this.next().fadeIn(); });
});

alternatively, you can just "pause" the chain, but you need to specify for how long:

$(this).fadeOut().next().delay(500).fadeIn();

How to create multiple output paths in Webpack config

You can only have one output path.

from the docs https://github.com/webpack/docs/wiki/configuration#output

Options affecting the output of the compilation. output options tell Webpack how to write the compiled files to disk. Note, that while there can be multiple entry points, only one output configuration is specified.

If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurenceOrderPlugin or recordsPath.

MySql Query Replace NULL with Empty String in Select

Try this, this should also get rid of those empty lines also:

SELECT prereq FROM test WHERE prereq IS NOT NULL;

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

There is slight change in mysql_real_escape_string mysqli_real_escape_string. below syntax

mysql_real_escape_string syntax will be mysql_real_escape_string($_POST['sample_var'])

mysqli_real_escape_string syntax will be mysqli_real_escape_string($conn,$_POST['sample_var'])

How to find index of list item in Swift?

tl;dr:

For classes, you might be looking for:

let index = someArray.firstIndex{$0 === someObject}

Full answer:

I think it's worth mentioning that with reference types (class) you might want to perform an identity comparison, in which case you just need to use the === identity operator in the predicate closure:


Swift 5, Swift 4.2:

let person1 = Person(name: "John")
let person2 = Person(name: "Sue")
let person3 = Person(name: "Maria")
let person4 = Person(name: "Loner")

let people = [person1, person2, person3]

let indexOfPerson1 = people.firstIndex{$0 === person1} // 0
let indexOfPerson2 = people.firstIndex{$0 === person2} // 1
let indexOfPerson3 = people.firstIndex{$0 === person3} // 2
let indexOfPerson4 = people.firstIndex{$0 === person4} // nil

Note that the above syntax uses trailing closures syntax, and is equivalent to:

let indexOfPerson1 = people.firstIndex(where: {$0 === person1})


Swift 4 / Swift 3 - the function used to be called index

Swift 2 - the function used to be called indexOf

* Note the relevant and useful comment by paulbailey about class types that implement Equatable, where you need to consider whether you should be comparing using === (identity operator) or == (equality operator). If you decide to match using ==, then you can simply use the method suggested by others (people.firstIndex(of: person1)).

Free Online Team Foundation Server

One of recent the TFS Rocks pocasts mentioned such an organisation, may have been number 16.

Splitting on first occurrence

>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'

WebDriver - wait for element using Java

This is how I do it in my code.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));

or

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));

to be precise.

See also:

Converting an int or String to a char array on Arduino

Just as a reference, here is an example of how to convert between String and char[] with a dynamic length -

// Define 
String str = "This is my string"; 

// Length (with one extra character for the null terminator)
int str_len = str.length() + 1; 

// Prepare the character array (the buffer) 
char char_array[str_len];

// Copy it over 
str.toCharArray(char_array, str_len);

Yes, this is painfully obtuse for something as simple as a type conversion, but sadly it's the easiest way.

How can I run a windows batch file but hide the command window?

Native C++ codified version of Oleg's answer -- this is copy/pasted from a project I work on under the Boost Software License.

BOOL noError;
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInformation;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
noError = CreateProcess(
    NULL,                                           //lpApplicationName
    //Okay the const_cast is bad -- this code was written a while ago.
    //should probably be &commandLine[0] instead. Oh, and commandLine is
    //a std::wstring
    const_cast<LPWSTR>(commandLine.c_str()),        //lpCommandLine
    NULL,                                           //lpProcessAttributes
    NULL,                                           //lpThreadAttributes
    FALSE,                                          //bInheritHandles
    CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,  //dwCreationFlags
    //This is for passing in a custom environment block -- you can probably
    //just use NULL here.
    options.e ? environment : NULL,                 //lpEnvironment
    NULL,                                           //lpCurrentDirectory
    &startupInfo,                                   //lpStartupInfo
    &processInformation                             //lpProcessInformation
);

if(!noError)
{
    return GetLastError();
}

DWORD exitCode = 0;

if (options.w) //Wait
{
    WaitForSingleObject(processInformation.hProcess, INFINITE);
    if (GetExitCodeProcess(processInformation.hProcess, &exitCode) == 0)
    {
        exitCode = (DWORD)-1;
    }
}

CloseHandle( processInformation.hProcess );
CloseHandle( processInformation.hThread );

Checking if a string array contains a value, and if so, getting its position

EDIT: I hadn't noticed you needed the position as well. You can't use IndexOf directly on a value of an array type, because it's implemented explicitly. However, you can use:

IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
    ...
}

(This is similar to calling Array.IndexOf as per Darin's answer - just an alternative approach. It's not clear to me why IList<T>.IndexOf is implemented explicitly in arrays, but never mind...)

ImportError: No module named 'bottle' - PyCharm

I had virtual env site package problem and this helped me, maybe it will help you too enter image description here

How can I generate a unique ID in Python?

This will work very quickly but will not generate random values but monotonously increasing ones (for a given thread).

import threading

_uid = threading.local()
def genuid():
    if getattr(_uid, "uid", None) is None:
        _uid.tid = threading.current_thread().ident
        _uid.uid = 0
    _uid.uid += 1
    return (_uid.tid, _uid.uid)

It is thread safe and working with tuples may have benefit as opposed to strings (shorter if anything). If you do not need thread safety feel free remove the threading bits (in stead of threading.local, use object() and remove tid altogether).

Hope that helps.

AngularJS - Trigger when radio button is selected

i prefer to use ng-value with ng-if, [ng-value] will handle trigger changes

<input type="radio"  name="isStudent" ng-model="isStudent" ng-value="true" />

//to show and hide input by removing it from the DOM, that's make me secure from malicious data

<input type="text" ng-if="isStudent"  name="textForStudent" ng-model="job">

S3 Static Website Hosting Route All Paths to Index.html

since the problem is still there I though I throw in another solution. My case was that I wanted to auto deploy all pull requests to s3 for testing before merge making them accessible on [mydomain]/pull-requests/[pr number]/
(ex. www.example.com/pull-requests/822/)

To the best of my knowledge non of s3 rules scenarios would allow to have multiple projects in one bucket using html5 routing so while above most voted suggestion works for a project in root folder, it doesn't for multiple projects in own subfolders.

So I pointed my domain to my server where following nginx config did the job

location /pull-requests/ {
    try_files $uri @get_files;
}
location @get_files {
    rewrite ^\/pull-requests\/(.*) /$1 break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @get_routes;
}

location @get_routes {
    rewrite ^\/(\w+)\/(.+) /$1/ break;
    proxy_pass http://<your-amazon-bucket-url>;
    proxy_intercept_errors on;
    recursive_error_pages on;
    error_page 404 = @not_found;
}

location @not_found {
    return 404;
}

it tries to get the file and if not found assumes it is html5 route and tries that. If you have a 404 angular page for not found routes you will never get to @not_found and get you angular 404 page returned instead of not found files, which could be fixed with some if rule in @get_routes or something.

I have to say I don't feel too comfortable in area of nginx config and using regex for that matter, I got this working with some trial and error so while this works I am sure there is room for improvement and please do share your thoughts.

Note: remove s3 redirection rules if you had them in S3 config.

and btw works in Safari

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

Pretty printing XML with javascript

Slight modification of efnx clckclcks's javascript function. I changed the formatting from spaces to tab, but most importantly I allowed text to remain on one line:

var formatXml = this.formatXml = function (xml) {
        var reg = /(>)\s*(<)(\/*)/g; // updated Mar 30, 2015
        var wsexp = / *(.*) +\n/g;
        var contexp = /(<.+>)(.+\n)/g;
        xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
        var pad = 0;
        var formatted = '';
        var lines = xml.split('\n');
        var indent = 0;
        var lastType = 'other';
        // 4 types of tags - single, closing, opening, other (text, doctype, comment) - 4*4 = 16 transitions 
        var transitions = {
            'single->single': 0,
            'single->closing': -1,
            'single->opening': 0,
            'single->other': 0,
            'closing->single': 0,
            'closing->closing': -1,
            'closing->opening': 0,
            'closing->other': 0,
            'opening->single': 1,
            'opening->closing': 0,
            'opening->opening': 1,
            'opening->other': 1,
            'other->single': 0,
            'other->closing': -1,
            'other->opening': 0,
            'other->other': 0
        };

        for (var i = 0; i < lines.length; i++) {
            var ln = lines[i];

            // Luca Viggiani 2017-07-03: handle optional <?xml ... ?> declaration
            if (ln.match(/\s*<\?xml/)) {
                formatted += ln + "\n";
                continue;
            }
            // ---

            var single = Boolean(ln.match(/<.+\/>/)); // is this line a single tag? ex. <br />
            var closing = Boolean(ln.match(/<\/.+>/)); // is this a closing tag? ex. </a>
            var opening = Boolean(ln.match(/<[^!].*>/)); // is this even a tag (that's not <!something>)
            var type = single ? 'single' : closing ? 'closing' : opening ? 'opening' : 'other';
            var fromTo = lastType + '->' + type;
            lastType = type;
            var padding = '';

            indent += transitions[fromTo];
            for (var j = 0; j < indent; j++) {
                padding += '\t';
            }
            if (fromTo == 'opening->closing')
                formatted = formatted.substr(0, formatted.length - 1) + ln + '\n'; // substr removes line break (\n) from prev loop
            else
                formatted += padding + ln + '\n';
        }

        return formatted;
    };

Can't create handler inside thread which has not called Looper.prepare()

You create handler in background thread this way

private void createHandler() {
        Thread thread = new Thread() {
          public void run() {
               Looper.prepare();

               final Handler handler = new Handler();
               handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // Do Work
                        handler.removeCallbacks(this);
                        Looper.myLooper().quit();
                   }
                }, 2000);

                Looper.loop();
            }
        };
        thread.start();
    }

Properties file with a list as the value for an individual key

Your logic is flawed... basically, you need to:

  1. get the list for the key
  2. if the list is null, create a new list and put it in the map
  3. add the word to the list

You're not doing step 2.

Here's the code you want:

Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
for (Map.Entry<Object, Object> entry : prop.entrySet())
{
    List<String> categoryList = categoryMap.get((String) entry.getKey());
    if (categoryList == null)
    {
        categoryList = new ArrayList<String>();
        LogDisplayService.categoryMap.put((String) entry.getKey(), categoryList);
    }
    categoryList.add((String) entry.getValue());
}

Note also the "correct" way to iterate over the entries of a map/properties - via its entrySet().

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.

More information on the answer can be found here

Linked Info Summary

Enable TLS 1.2 at the system (SCHANNEL) level:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

(equivalent keys are probably also available for other TLS versions)

Tell .NET Framework to use the system TLS versions:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001

This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.

Numpy - add row to array

If you can do the construction in a single operation, then something like the vstack-with-fancy-indexing answer is a fine approach. But if your condition is more complicated or your rows come in on the fly, you may want to grow the array. In fact the numpythonic way to do something like this - dynamically grow an array - is to dynamically grow a list:

A = np.array([[1,2,3],[4,5,6]])
Alist = [r for r in A]
for i in range(100):
    newrow = np.arange(3)+i
    if i%5:
        Alist.append(newrow)
A = np.array(Alist)
del Alist

Lists are highly optimized for this kind of access pattern; you don't have convenient numpy multidimensional indexing while in list form, but for as long as you're appending it's hard to do better than a list of row arrays.

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Always use EntityFunctions.TruncateTime() for both x.DateTimeStart and currentDate. such as :

var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == EntityFunctions.TruncateTime(currentDate));

Failed to locate the winutils binary in the hadoop binary path

The statement java.io.IOException: Could not locate executable null\bin\winutils.exe

explains that the null is received when expanding or replacing an Environment Variable. If you see the Source in Shell.Java in Common Package you will find that HADOOP_HOME variable is not getting set and you are receiving null in place of that and hence the error.

So, HADOOP_HOME needs to be set for this properly or the variable hadoop.home.dir property.

Hope this helps.

Thanks, Kamleshwar.

Editor does not contain a main type in Eclipse

Right click on your project, select New -> Source Folder

Enter src as Folder name, then click finish.

Eclipse will then recognize the src folder as containing Java code, and you should be able to set up a run configuration

How to enable C++11 in Qt Creator?

According to this site add

CONFIG += c++11

to your .pro file (see at the bottom of that web page). It requires Qt 5.


The other answers, suggesting

QMAKE_CXXFLAGS += -std=c++11 (or QMAKE_CXXFLAGS += -std=c++0x)

also work with Qt 4.8 and gcc / clang.

Xcode swift am/pm time to 24 hour format

let calendar = Calendar.current
let hours    = calendar.component(.hour, from: Date())
let minutes  = calendar.component(.minute, from: Date())
let seconds  = calendar.component(.second, from: Date())

How do you specify the Java compiler version in a pom.xml file?

maven-compiler-plugin it's already present in plugins hierarchy dependency in pom.xml. Check in Effective POM.

For short you can use properties like this:

<properties>
   <maven.compiler.source>1.8</maven.compiler.source>
   <maven.compiler.target>1.8</maven.compiler.target>
</properties>

I'm using Maven 3.2.5.

How to place two divs next to each other?

This is the right CSS3 answer. Hope this helps you somehow now :D I really recommend you to read the book: https://www.amazon.com/Book-CSS3-Developers-Future-Design/dp/1593272863 Actually I have made this solution from reading this book now. :D

_x000D_
_x000D_
#wrapper{_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#first{_x000D_
  width: 300px;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
#second{_x000D_
  border: 1px solid green;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
    <div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
    <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

Use SQL Server's date styles to pre-format your date values.

SELECT
    CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero  -- Date Style 101 = mm/dd/yyyy
    ,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero   -- Date Style 103 = dd/mm/yyyy

Angular.js How to change an elements css class on click and to remove all others

I only change/remove the class:

   function removeClass() {
                    var element = angular.element('#nameInput');
          element.removeClass('nameClass');
   };

How can I show three columns per row?

Try this one using Grid Layout:

_x000D_
_x000D_
.grid-container {_x000D_
  display: grid;_x000D_
  grid-template-columns: auto auto auto;_x000D_
  padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
  background-color: rgba(255, 255, 255, 0.8);_x000D_
  border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
  padding: 20px;_x000D_
  font-size: 30px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
  <div class="grid-item">1</div>_x000D_
  <div class="grid-item">2</div>_x000D_
  <div class="grid-item">3</div>  _x000D_
  <div class="grid-item">4</div>_x000D_
  <div class="grid-item">5</div>_x000D_
  <div class="grid-item">6</div>  _x000D_
  <div class="grid-item">7</div>_x000D_
  <div class="grid-item">8</div>_x000D_
  <div class="grid-item">9</div>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Truncate/round whole number in JavaScript?

I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:

function truncateToInt(x)
{
    if(x > 0)
    {
         return Math.floor(x);
    }
    else
    {
         return Math.ceil(x);
    }
 }

Then:

y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3

Notice: This answer was written when Math.trunc(x) was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x).

jQuery If DIV Doesn't Have Class "x"

jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class

if (!$(this).hasClass("selected")) {
    //do stuff
}

Take a look at my example of use

  • If you hover over a div, it fades as normal speed to 100% opacity if the div does not contain the 'selected' class
  • If you hover out of a div, it fades at slow speed to 30% opacity if the div does not contain the 'selected' class
  • Clicking the button adds 'selected' class to the red div. The fading effects no longer work on the red div

Here is the code for it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>


<!-- jQuery code here -->
<script type="text/javascript">
$(function() {

$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});

$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );

$('.thumbs').hover(fadeItIn, fadeItOut);


});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}
</script>


</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>

EDIT:

this is just a guess, but are you trying to achieve something like this?

  • Both divs start at 30% opacity
  • Hovering over a div fades to 100% opacity, hovering out fades back to 30% opacity. Fade effects only work on elements that don't have the 'selected' class
  • Clicking a div adds/removes the 'selected' class

jQuery Code is here-

$(function() {

$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);

});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}

<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>

How to display Woocommerce Category image?

To display the category image for the currently displayed category in archive-product.php, use the current category term_id when is_product_category() is true:

// verify that this is a product category page
if ( is_product_category() ){
    global $wp_query;

    // get the query object
    $cat = $wp_query->get_queried_object();

    // get the thumbnail id using the queried category term_id
    $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true ); 

    // get the image URL
    $image = wp_get_attachment_url( $thumbnail_id ); 

    // print the IMG HTML
    echo "<img src='{$image}' alt='' width='762' height='365' />";
}

Permission is only granted to system app

Path In Android Studio in mac:

Android Studio -> Preferences -> Editor -> Inspections

Expand Android -> Expand Lint -> Expand Correctness

Uncheck the checkbox for Using system app permission

Click on "APPLY" -> "OK"

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

https://stackoverflow.com/a/16350929/11860907

If you add e.SuppressKeyPress = true; as shown in the answer in this link you will suppress the annoying ding sound that occurs.

How to compare two maps by their values

Since you asked about ready-made Api's ... well Apache's commons. collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union.

What is the preferred/idiomatic way to insert into a map?

As of C++11, you have two major additional options. First, you can use insert() with list initialization syntax:

function.insert({0, 42});

This is functionally equivalent to

function.insert(std::map<int, int>::value_type(0, 42));

but much more concise and readable. As other answers have noted, this has several advantages over the other forms:

  • The operator[] approach requires the mapped type to be assignable, which isn't always the case.
  • The operator[] approach can overwrite existing elements, and gives you no way to tell whether this has happened.
  • The other forms of insert that you list involve an implicit type conversion, which may slow your code down.

The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.

Second, you can use the emplace() method:

function.emplace(0, 42);

This is more concise than any of the forms of insert(), works fine with move-only types like unique_ptr, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace methods aren't usually used that way.

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

Rollback transaction after @Test

The answers mentioning adding @Transactional are correct, but for simplicity you could just have your test class extends AbstractTransactionalJUnit4SpringContextTests.

Select unique values with 'select' function in 'dplyr' library

In dplyr 0.3 this can be easily achieved using the distinct() method.

Here is an example:

distinct_df = df %>% distinct(field1)

You can get a vector of the distinct values with:

distinct_vector = distinct_df$field1

You can also select a subset of columns at the same time as you perform the distinct() call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:

distinct_df = df %>% distinct(field1) %>% select(field1) distinct_vector = distinct_df$field1

Conditional formatting using AND() function

You can use a much simpler formula. I just created a new workbook to test it.

Column A = Date1 | Column B = Date2 | Column C = Date3

Highlight Column A and enter the conditional formatting formula:

=AND(A1>B1,A1<C1)

Break string into list of characters in Python

You can do this using list:

new_list = list(fL)

Be aware that any spaces in the line will be included in this list, to the best of my knowledge.

TimeSpan to DateTime conversion

An easy method, use ticks:

new DateTime((DateTime.Now - DateTime.Now.AddHours(-1.55)).Ticks).ToString("HH:mm:ss:fff")

This function will give you a date (Without Day / Month / Year)

How to declare a variable in MySQL?

There are mainly three types of variables in MySQL:

  1. User-defined variables (prefixed with @):

    You can access any user-defined variable without declaring it or initializing it. If you refer to a variable that has not been initialized, it has a value of NULL and a type of string.

    SELECT @var_any_var_name
    

    You can initialize a variable using SET or SELECT statement:

    SET @start = 1, @finish = 10;    
    

    or

    SELECT @start := 1, @finish := 10;
    
    SELECT * FROM places WHERE place BETWEEN @start AND @finish;
    

    User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.

    User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients.

    They can be used in SELECT queries using Advanced MySQL user variable techniques.

  2. Local Variables (no prefix) :

    Local variables needs to be declared using DECLARE before accessing it.

    They can be used as local variables and the input parameters inside a stored procedure:

    DELIMITER //
    
    CREATE PROCEDURE sp_test(var1 INT) 
    BEGIN   
        DECLARE start  INT unsigned DEFAULT 1;  
        DECLARE finish INT unsigned DEFAULT 10;
    
        SELECT  var1, start, finish;
    
        SELECT * FROM places WHERE place BETWEEN start AND finish; 
    END; //
    
    DELIMITER ;
    
    CALL sp_test(5);
    

    If the DEFAULT clause is missing, the initial value is NULL.

    The scope of a local variable is the BEGIN ... END block within which it is declared.

  3. Server System Variables (prefixed with @@):

    The MySQL server maintains many system variables configured to a default value. They can be of type GLOBAL, SESSION or BOTH.

    Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.

    To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT @@var_name.

    SHOW VARIABLES LIKE '%wait_timeout%';
    
    SELECT @@sort_buffer_size;
    

    They can be set at server startup using options on the command line or in an option file. Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:

    -- Syntax to Set value to a Global variable:
    SET GLOBAL sort_buffer_size=1000000;
    SET @@global.sort_buffer_size=1000000;
    
    -- Syntax to Set value to a Session variable:
    SET sort_buffer_size=1000000;
    SET SESSION sort_buffer_size=1000000;
    SET @@sort_buffer_size=1000000;
    SET @@local.sort_buffer_size=10000;
    

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

Background position, margin-top?

#div-name

{

  background-image: url('../images/background-art-main.jpg');
  background-position: top right 50px;
  background-repeat: no-repeat;
}

A top-like utility for monitoring CUDA activity on a GPU

You can use the monitoring program glances with its GPU monitoring plug-in:

  • open source
  • to install: sudo apt-get install -y python-pip; sudo pip install glances[gpu]
  • to launch: sudo glances

enter image description here

It also monitors the CPU, disk IO, disk space, network, and a few other things:

enter image description here

Pandas DataFrame to List of Lists

We can use the DataFrame.iterrows() function to iterate over each of the rows of the given Dataframe and construct a list out of the data of each row:

# Empty list 
row_list =[] 

# Iterate over each row 
for index, rows in df.iterrows(): 
    # Create list for the current row 
    my_list =[rows.Date, rows.Event, rows.Cost] 

    # append the list to the final list 
    row_list.append(my_list) 

# Print 
print(row_list) 

We can successfully extract each row of the given data frame into a list

Changing the space between each item in Bootstrap navbar

As of Bootstrap 4, you can use the spacing utilities.

Add for instance px-2 in the classes of the nav-item to increase the padding.

How to read XML using XPath in Java

Here is an example of processing xpath with vtd-xml... for heavy duty XML processing it is second to none. here is the a recent paper on this subject Processing XML with Java – A Performance Benchmark

import com.ximpleware.*;

public class changeAttrVal {
    public  static  void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        XMLModifier xm = new XMLModifier(vn);
        ap.selectXPath("/*/place[@id=\"p14\" and   @initialMarking=\"2\"]/@initialMarking");
        int i=0;
        while((i=ap.evalXPath())!=-1){
            xm.updateToken(i+1, "499");// change initial marking from 2 to 499
        }
        xm.output("new.xml");
    }

}

how to permit an array with strong parameters

It should be like

params.permit(:id => [])

Also since rails version 4+ you can use:

params.permit(id: [])

C# : Out of Memory exception

Two points:

  1. If you are running a 32 bit Windows, you won't have all the 4GB accessible, only 2GB.
  2. Don't forget that the underlying implementation of List is an array. If your memory is heavily fragmented, there may not be enough contiguous space to allocate your List, even though in total you have plenty of free memory.

Create pandas Dataframe by appending one row at a time

Figured out a simple and nice way:

>>> df
     A  B  C
one  1  2  3
>>> df.loc["two"] = [4,5,6]
>>> df
     A  B  C
one  1  2  3
two  4  5  6

Note the caveat with performance as noted in the comments

Creating a JSON Array in node js

You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.

Use JSON.stringify(object) to turn it into (a string of) JSON text.

Hard reset of a single file

You can use the following command:

git reset -- my-file.txt

which will update both the working copy of my-file.txt when added.

How to get the Mongo database specified in connection string in C#

With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:

const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");

How to import a single table in to mysql database using command line

Importing the Single Table

To import a single table into an existing database you would use the following command:

mysql -u username -p -D database_name < tableName.sql

Note:It is better to use full path of the sql file tableName.sql

What is Python used for?

Why should you learn Python Programming Language?

Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's

  • Easy to Read & Easy to Learn
  • Very productive or small as well as big projects
  • Big libraries for many things

enter image description here

What is Python Programming Language used for?

As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:

Web Development:

You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.

Data Analysis:

Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.

Machine Learning:

What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.

Computer Vision:

You can do many interesting things such as Face detection, Color detection while using Opencv and Python.

Internet Of Things With Raspberry Pi:

Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!

Game Development:

Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.

Web Scraping:

If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.

Writing Scripts:

If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.

Browser Automation:

Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.

GUI Development:

Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.

Rapid Prototyping:

Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.

Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.

How to change fontFamily of TextView in Android

It's the same as android:typeface.

built-in fonts are:

  • normal
  • sans
  • serif
  • monospace

See android:typeface.

Thread Safe C# Singleton Pattern

You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton() { }

    public static Singleton Instance()
    {
        return instance;
    }
}

how to get current location in google map android

Why not to use FusedLocationApi instead of OnMyLocationChangeListener? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates() method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect GoogleApiClient.

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

C++ - unable to start correctly (0xc0150002)

I agree with Brandrew, the problem is most likely caused by some missing dlls that can't be found neither on the system path nor in the folder where the executable is. Try putting the following DLLs nearby the executable:

  • the Visual Studio C++ runtime (in VS2008, they could be found at places like C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86.) Include all 3 of the DLL files as well as the manifest file.
  • the four OpenCV dlls (cv210.dll, cvaux210.dll, cxcore210.dll and highgui210.dll, or the ones your OpenCV version has)
  • if that still doesn't work, try the debug VS runtime (executables compiled for "Debug" use a different set of dlls, named something like msvcrt9d.dll, important part is the "d")

Alternatively, try loading the executable into Dependency Walker ( http://www.dependencywalker.com/ ), it should point out the missing dlls for you.

HTML5 Number Input - Always show 2 decimal places

This works to enforce a max of 2 decimal places without automatically rounding to 2 places if the user isn't finished typing.

function naturalRound(e) {

   let dec = e.target.value.indexOf(".")
   let tooLong = e.target.value.length > dec + 3
   let invalidNum = isNaN(parseFloat(e.target.value))

   if ((dec >= 0 && tooLong) || invalidNum) {
     e.target.value = e.target.value.slice(0, -1)
   }
}

Date in mmm yyyy format in postgresql

You can write your select query as,

select * from table_name where to_char(date_time_column, 'YYYY-MM')  = '2011-03';

How do I increase the scrollback buffer in a running screen session?

WARNING: setting this value too high may cause your system to experience a significant hiccup. The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session. I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).

Add vertical scroll bar to panel

Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)

mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;

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

from the commandline:

chkdsk l: (wait for the scan to finish)

sizdir32 http://www.ltr-data.se/opencode.html/

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Tag your action:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

For ASP.NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Tag a whole API controller:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

For Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code

Disable sorting for a particular column in jQuery DataTables

$("#example").dataTable(
  {
    "aoColumnDefs": [{
      "bSortable": false, 
      "aTargets": [0, 1, 2, 3, 4, 5]
    }]
  }
);

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

How to see the changes between two commits without commits in-between?

What about this:

git diff abcdef 123456 | less

It's handy to just pipe it to less if you want to compare many different diffs on the fly.

Clear icon inside input text

I've created a clearable textbox in just CSS. It requires no javascript code to make it work

below is the demo link

http://codepen.io/shidhincr/pen/ICLBD

What is REST? Slightly confused

REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.

The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:

/posts Would be how a user would access ALL the posts, for displaying.

/posts/:id Would be how a user would access and view an individual post, retrieved based on their unique id.

/posts/new Would be how you would display a form for creating a new post.

Sending a POST request to /users would be how you would actually create a new post on the database level.

Sending a PUT request to /users/:id would be how you would update the attributes of a given post, again identified by a unique id.

Sending a DELETE request to /users/:id would be how you would delete a given post, again identified by a unique id.

As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.

I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).

When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

My simple solution:

$("form").children('input[type="submit"]').click();

It is work for me.

Can a local variable's memory be accessed outside its scope?

You actually invoked undefined behaviour.

Returning the address of a temporary works, but as temporaries are destroyed at the end of a function the results of accessing them will be undefined.

So you did not modify a but rather the memory location where a once was. This difference is very similar to the difference between crashing and not crashing.

Compare string with all values in list

for word in d:
    if d in paid[j]:
         do_something()

will try all the words in the list d and check if they can be found in the string paid[j].

This is not very efficient since paid[j] has to be scanned again for each word in d. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.

sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]

s1 = set(sentence.split())
s2 = set(d)

print (s1.intersection(s2))

Output:

{'come', 'easy'}

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

Angularjs: input[text] ngChange fires while the value is changing

In case anyone else looking for additional "enter" keypress support, here's an update to the fiddle provided by Gloppy

Code for keypress binding:

elm.bind("keydown keypress", function(event) {
    if (event.which === 13) {
        scope.$apply(function() {
            ngModelCtrl.$setViewValue(elm.val());
        });
    }
});

Interface/enum listing standard mime-type constants

Guava library

We have a Guava class for this: com.google.common.net.MediaType.

It was released with Guava 12 as stated in the source code and in Issue 823. Sources are available, too.

What is the difference between canonical name, simple name and class name in Java Class?

this is best document I found describing getName(), getSimpleName(), getCanonicalName()

https://javahowtodoit.wordpress.com/2014/09/09/java-lang-class-what-is-the-difference-between-class-getname-class-getcanonicalname-and-class-getsimplename/

// Primitive type
int.class.getName();          // -> int
int.class.getCanonicalName(); // -> int
int.class.getSimpleName();    // -> int

// Standard class
Integer.class.getName();          // -> java.lang.Integer
Integer.class.getCanonicalName(); // -> java.lang.Integer
Integer.class.getSimpleName();    // -> Integer

// Inner class
Map.Entry.class.getName();          // -> java.util.Map$Entry
Map.Entry.class.getCanonicalName(); // -> java.util.Map.Entry
Map.Entry.class.getSimpleName();    // -> Entry     

// Anonymous inner class
Class<?> anonymousInnerClass = new Cloneable() {}.getClass();
anonymousInnerClass.getName();          // -> somepackage.SomeClass$1
anonymousInnerClass.getCanonicalName(); // -> null
anonymousInnerClass.getSimpleName();    // -> // An empty string

// Array of primitives
Class<?> primitiveArrayClass = new int[0].getClass();
primitiveArrayClass.getName();          // -> [I
primitiveArrayClass.getCanonicalName(); // -> int[]
primitiveArrayClass.getSimpleName();    // -> int[]

// Array of objects
Class<?> objectArrayClass = new Integer[0].getClass();
objectArrayClass.getName();          // -> [Ljava.lang.Integer;
objectArrayClass.getCanonicalName(); // -> java.lang.Integer[]
objectArrayClass.getSimpleName();    // -> Integer[]

Converting list to *args when calling function

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

so:

>>> def printer(*args):
 print args


>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>> 

Why is this rsync connection unexpectedly closed on Windows?

i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.

A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync

Java - Abstract class to contain variables?

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

Node Multer unexpected field

The <NAME> you use in multer's upload.single(<NAME>) function must be the same as the one you use in <input type="file" name="<NAME>" ...>.

So you need to change

var type = upload.single('file')

to

var type = upload.single('recfile')

in you app.js

Hope this helps.

How to get the containing form of an input?

And one more....

var _e = $(e.target); // e being the event triggered
var element = _e.parent(); // the element the event was triggered on
console.log("_E " + element.context); // [object HTMLInputElement]
console.log("_E FORM " + element.context.form); // [object HTMLFormElement]
console.log("_E FORM " + element.context.form.id); // form id

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

How to specify credentials when connecting to boto3 S3?

You can create a session:

import boto3
session = boto3.Session(
    aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
    aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY,
)

Then use that session to get an S3 resource:

s3 = session.resource('s3')

How to render pdfs using C#

Google has open sourced its excellent PDF rendering engine - PDFium - that it wrote with Foxit Software.

There is a C# nuget package called PdfiumViewer which gives a C# wrapper around PDFium and allows PDFs to be displayed and printed.

I have used it and was very impressed with the quality of the rendering.


PDFium works directly with streams so it doesn't require any data to be written to disk.

This is my example from a WinForms app

    public void LoadPdf(byte[] pdfBytes)
    {
        var stream = new MemoryStream(pdfBytes);
        LoadPdf(stream)
    }

    public void LoadPdf(Stream stream)
    {
        // Create PDF Document
        var pdfDocument = PdfDocument.Load(stream);

        // Load PDF Document into WinForms Control
        pdfRenderer.Load(pdfDocument);
    }

Edit: To get the pdfRenderer control in WinForm: Add the PdfiumViewer NuGet package to the project; open the projects packages folder in Windows Explorer and drag the PdfiumViewer.dll file onto the Toolbox window; A control called PdfRenderer will be available to add:

Adding PdfRenderer control to WinForms

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Get Bitmap attached to ImageView

For those who are looking for Kotlin solution to get Bitmap from ImageView.

var bitmap = (image.drawable as BitmapDrawable).bitmap

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

I had the same problem. All i did was - From the pom.xml file i deleted the dependency for junit 3.8 and added a new dependency for junit 4.8. Then i did maven clean and maven install. It did the trick. To verify , after maven install i went project->properties-build path->maven dependencies and saw that now the junit 3.8 jar is gone !, instead junit 4.8 jar is listed. cool!!. Now my test runs like a charm.. Hope this helps somehow..

Where to find Java JDK Source Code?

Here the official link for jdk source. http://www.oracle.com/technetwork/java/javase/downloads/index.html (you may need to scroll to the bottom of the page)

Difference between numpy dot() and Python 3.5+ matrix multiplication @

In mathematics, I think the dot in numpy makes more sense

dot(a,b)_{i,j,k,a,b,c} = formula

since it gives the dot product when a and b are vectors, or the matrix multiplication when a and b are matrices


As for matmul operation in numpy, it consists of parts of dot result, and it can be defined as

>matmul(a,b)_{i,j,k,c} = formula

So, you can see that matmul(a,b) returns an array with a small shape, which has smaller memory consumption and make more sense in applications. In particular, combining with broadcasting, you can get

matmul(a,b)_{i,j,k,l} = formula

for example.


From the above two definitions, you can see the requirements to use those two operations. Assume a.shape=(s1,s2,s3,s4) and b.shape=(t1,t2,t3,t4)

  • To use dot(a,b) you need

    1. t3=s4;
  • To use matmul(a,b) you need

    1. t3=s4
    2. t2=s2, or one of t2 and s2 is 1
    3. t1=s1, or one of t1 and s1 is 1

Use the following piece of code to convince yourself.

Code sample

import numpy as np
for it in xrange(10000):
    a = np.random.rand(5,6,2,4)
    b = np.random.rand(6,4,3)
    c = np.matmul(a,b)
    d = np.dot(a,b)
    #print 'c shape: ', c.shape,'d shape:', d.shape

    for i in range(5):
        for j in range(6):
            for k in range(2):
                for l in range(3):
                    if not c[i,j,k,l] == d[i,j,k,j,l]:
                        print it,i,j,k,l,c[i,j,k,l]==d[i,j,k,j,l] #you will not see them

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

This can happen if you accidentally are not dragging the element that does have an id assigned (for example you are dragging the surrounding element). In that case the ID is empty and the function drag() is assigning an empty value which is then passed to drop() and fails there.

Try assigning the ids to all of your elements, including the tds, divs, or whatever is around your draggable element.

Order discrete x scale by frequency/value

You can use reorder:

qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")

Edit:

To have the tallest bar at the left, you have to use a bit of a kludge:

qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
   data=mtcars,geom="bar")

I would expect this to also have negative heights, but it doesn't, so it works!

Scala how can I count the number of occurrences in a list

scala> val list = List(1,2,4,2,4,7,3,2,4)
list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)

scala> println(list.filter(_ == 2).size)
3

Write a file in UTF-8 using FileWriter (Java)?

OK it's 2019 now, and from Java 11 you have a constructor with Charset:

FileWriter?(String fileName, Charset charset)

Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)