Programs & Examples On #Twilio

Twilio is a set of web services and tools by the eponymous company to do text/picture messages, phone calls, and embed VoIP functions into web and mobile applications.

Data truncated for column?

I had the same problem because of an table column which was defined as ENUM('x','y','z') and later on I was trying to save the value 'a' into this column, thus I got the mentioned error.

Solved by altering the table column definition and added value 'a' into the enum set.

How to get the row number from a datatable?

int index = dt.Rows.IndexOf(row);

But you're probably better off using a for loop instead of foreach.

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

How to get SLF4J "Hello World" working with log4j?

you need to add 3 dependency ( API+ API implementation + log4j dependency) 
Add also this 
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.5</version>
</dependency>

# And to see log in command line , set log4j.properties 

# Root logger option
log4j.rootLogger=INFO, file, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

#And to see log in file  , set log4j.properties 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./logs/logging.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

How to check existence of user-define table type in SQL Server 2008?

IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyType')
    --stuff

sys.types... they aren't schema-scoped objects so won't be in sys.objects

Update, Mar 2013

You can use TYPE_ID too

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

Why are only a few video games written in Java?

Game marketing is a commercial process; publishers want quantifiable low-risk returns on their investment. As a consequence, the focus is usually on technology gimmicks (with exceptions) that consumers will buy to produce reliable return - these tend to be superficial visual effects such as lens glare or higher resolution. These effects are reliable because they simply use increases in processing power - they exploit the hardware/Moore's law increases. this implies using C/C++ - java is usually too abstracted from the hardware to exploit these benefits.

Can I use an HTML input type "date" to collect only a year?

No, you can't, it doesn't support only year, so to do that you need a script, like jQuery or the webshim link you have, which shows year only.


If jQuery would be an option, here is one, borrowed from Sibu:

Javascript

$(function() {
    $( "#datepicker" ).datepicker({dateFormat: 'yy'});
});?

CSS

.ui-datepicker-calendar {
   display: none;
}

Src: https://stackoverflow.com/a/13528855/2827823

Src fiddle: http://jsfiddle.net/vW8zc/

Here is an updated fiddle, without the month and prev/next buttons


If bootstrap is an option, check this link, they have a layout how you want.

Debug JavaScript in Eclipse

I'm not a 100% sure but I think Aptana let's you do that.

How to get pandas.DataFrame columns containing specific dtype

You can also try to get the column names from panda data frame that returns columnn name as well dtype. here i'll read csv file from https://mlearn.ics.uci.edu/databases/autos/imports-85.data but you have define header that contain columns names.

import pandas as pd

url="https://mlearn.ics.uci.edu/databases/autos/imports-85.data"

df=pd.read_csv(url,header = None)

headers=["symboling","normalized-losses","make","fuel-type","aspiration","num-of-doors","body-style",
         "drive-wheels","engine-location","wheel-base","length","width","height","curb-weight","engine-type",
         "num-of-cylinders","engine-size","fuel-system","bore","stroke","compression-ratio","horsepower","peak-rpm"
         ,"city-mpg","highway-mpg","price"]

df.columns=headers

print df.columns

Getting datarow values into a string?

Your rows object holds an Item attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString() on the row. You should access each column from the row separately, use a for or a foreach to walk the array of columns.

Here, take a look at the class:

http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx

MySQL: Insert record if not exists in table

I had a problem, and the method Mike advised worked partly, I had an error Dublicate Column name = '0', and changed the syntax of your query as this`

     $tQ = "INSERT  INTO names (name_id, surname_id, sum, sum2, sum3,sum4,sum5) 
                SELECT '$name', '$surname', '$sum', '$sum2', '$sum3','$sum4','$sum5' 
FROM DUAL
                WHERE NOT EXISTS (
                SELECT sum FROM names WHERE name_id = '$name' 
AND surname_id = '$surname') LIMIT 1;";

The problem was with column names. sum3 was equal to sum4 and mysql throwed dublicate column names, and I wrote the code in this syntax and it worked perfectly,

android.content.Context.getPackageName()' on a null object reference

The answers to this question helped me find my problem, but my source was different, so hopefully this can shed light on someone finding this page searching for answers to the 'random' context crash:

I had specified a SharedPreferences object, and tried to instantiate it at it's class-level declaration, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref =
        PreferenceManager.getDefaultSharedPreferences(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //...

Referencing this before the onCreate caused the "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference" error for me.

Instantiating the object inside the onCreate() solved my problem, like so:

public class MyFragment extends FragmentActivity {
    private SharedPreferences sharedPref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

Hope that helps.

What is the difference between Bootstrap .container and .container-fluid classes?

I think you are saying that a container vs container-fluid is the difference between responsive and non-responsive to the grid. This is not true...what is saying is that the width is not fixed...its full width!

This is hard to explain so lets look at the examples


Example one

container-fluid:

http://www.bootply.com/119981

So you see how the container takes up the whole screen...that's a container-fluid.

Now lets look at the other just a normal container and watch the edges of the preview

Example two

container

http://www.bootply.com/119982

Now do you see the white space in the example? That's because its a fixed width container ! It might make more sense to open both examples up in two different tabs and switch back and forth.

EDIT

Better yet here is an example with both containers at once! Now you can really tell the difference!

http://www.bootply.com/119983

I hope this helped clarify a little bit!

An URL to a Windows shared folder

If you are allowed to go further then javascript/html facilities - I would use the apache web server to represent your directory listing via http.

If this solution is appropriate. these are the steps:

  1. download apache hhtp server from one of the mirrors http://httpd.apache.org/download.cgi

  2. unzip/install (if msi) it to the directory e.g C:\opt\Apache (the instruction is for windows)

  3. map the network forlder as a local drive on windows (\server\folder to let's say drive H:)

  4. open conf/httpd.conf file

  5. make sure the next line is present and not commented

    LoadModule autoindex_module modules/mod_autoindex.so

  6. Add directory configuration

<Directory "H:/path">

Options +Indexes

AllowOverride None

Order allow,deny

Allow from all

</Directory> 7. Start the web server and make sure the directory listingof the remote folder is available by http. hit localhost/path 8. use a frame inside your web page to access the listing

What is missed: 1. you mignt need more fancy configuration for the host name, refer to Apache Web Server docs. Register the host name in DNS server

  1. the mapping to the network drive might not work, i did not check. As a posible resolution - host your web server on the same machine as smb server.

python - if not in list

Your code should work, but you can also try:

    if not item in mylist :

How to style a clicked button in CSS

There are three states of button

  • Normal : You can select like this button
  • Hover : You can select like this button:hover
  • Pressed/Clicked : You can select like this button:active

Normal:

.button
 {
     //your css
 }

Active

 .button:active
{
        //your css
}

Hover

 .button:hover
{
        //your css
}

SNIPPET:

Use :active to style the active state of button.

_x000D_
_x000D_
button:active{_x000D_
   background-color:red;_x000D_
}
_x000D_
<button>Click Me</button>
_x000D_
_x000D_
_x000D_

How do I pass a method as a parameter in Python

Yes it is possible. Just call it:

class Foo(object):
    def method1(self):
        pass
    def method2(self, method):
        return method()

foo = Foo()
foo.method2(foo.method1)

How to set entire application in portrait mode only?

Write this to your manifest file, for every activity:

android:screenOrientation="portrait" 

'adb' is not recognized as an internal or external command, operable program or batch file

just open Android studio and press "Tools" on Top navigation bar

tools->SDK Manager

Where you can get SDK location

Open SDK folder -> platform-tools

Ant build failed: "Target "build..xml" does not exist"

I'm probably late but this worked for me:


  1. Open your build.xml file located in your project's directory.
  2. Copy and Paste the following code in the main project tag : <target name="build" />

jQuery adding 2 numbers from input fields

There are two way that you can add two number in jQuery

First way:

var x = parseInt(a) + parseInt(b);
alert(x);

Second Way:

var x = parseInt(a+2);
alert(x);

Now come your question

var a = parseInt($("#a").val()); 
var b = parseInt($("#b").val());
alert(a+b);

ComboBox- SelectionChanged event has old value, not new value

The second option didn't work for me because the .Text element was out of scope (C# 4.0 VS2008). This was my solution...

string test = null;
foreach (ComboBoxItem item in e.AddedItems)
{
   test = item.Content.ToString();
   break;
}

How to center an element in the middle of the browser window?

Here is:

  • HTML+CSS only solution - no JavaScript needed
  • It does not require that you to know the content size in advance
  • The content stands centered on window resizing

And the example:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML centering</title>

        <style type="text/css">
        <!--
        html, body, #tbl_wrap { height: 100%; width: 100%; padding: 0; margin: 0; }
        #td_wrap { vertical-align: middle; text-align: center; }
        -->
        </style>
    </head>

    <body>
        <table id="tbl_wrap"><tbody><tr><td id="td_wrap">
        <!-- START: Anything between these wrapper comment lines will be centered -->


<div style="border: 1px solid black; display: inline-block;">
This content will be centered.
</div>

        <!-- END: Anything between these wrapper comment lines will be centered -->
        </td></tr></tbody></table>
    </body>
</html>

Take a look at the original URL for full info: http://krustev.net/html_center_content.html

You can do whatever you like with this code. The only condition is that any derived work must have a reference to the original author.

Loop timer in JavaScript

You should try something like this:

 function update(){
    i++;
    document.getElementById('tekst').innerHTML = i;
    setInterval(update(),1000);
    }

This means that you have to create a function in which you do the stuff you need to do, and make sure it will call itself with an interval you like. In your body onload call the function for the first time like this:

<body onload="update()">

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

End-line characters from lines read from text file, using Python

Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that:

if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1)) 
  line input #1 a$
  print a$
wend
close

Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:

def line_input (file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line_input(f):
    # do something with line

I am induced to think that something has gone the wrong way somewhere...

jQuery Set Selected Option Using Next

This is what i just used, i like how clean it is :-)

$('select').val(function(){
    var nextOption = $(this).children(':selected').next();
    return $(nextOption).val();
}).change();

Why doesn't the height of a container element increase if it contains floated elements?

Its because of the float of the div. Add overflow: hidden on the outside element.

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

Demo

CSS3 Spin Animation

The only answer which gives the correct 359deg:

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(359deg); }
}

&.active {
  animation: spin 1s linear infinite;
}

Here's a useful gradient so you can prove it is spinning (if its a circle):

background: linear-gradient(to bottom, #000000 0%,#ffffff 100%);

How to obtain values of request variables using Python and Flask

You can get posted form data from request.form and query string data from request.args.

myvar =  request.form["myvar"]
myvar = request.args["myvar"]

Multiple bluetooth connection

Two UE Boom Bluetooth speakers can form a stereo, which means the phone can stream simultaneously to two Bluetooth devices. The reason is Bluetooth 4.0 can support up to two synchronous connection oriented (SCO) links on the same piconet, and A2DP is based on SCO link.

Your demand "bluetooth chat" is based on SPP profile, and SPP is based on RFCOMM protocol. Luckily even Bluetooth 2.1 can support multiple RFCOMM channels, so yes, you can have multiple bluetooth connection to chat with each other.

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

Downloading a picture via urllib and python

If you need proxy support you can do this:

  if needProxy == False:
    returnCode, urlReturnResponse = urllib.urlretrieve( myUrl, fullJpegPathAndName )
  else:
    proxy_support = urllib2.ProxyHandler({"https":myHttpProxyAddress})
    opener = urllib2.build_opener(proxy_support)
    urllib2.install_opener(opener)
    urlReader = urllib2.urlopen( myUrl ).read() 
    with open( fullJpegPathAndName, "w" ) as f:
      f.write( urlReader )

Doing HTTP requests FROM Laravel to an external API

As of Laravel v7.X, the framework now comes with a minimal API wrapped around the Guzzle HTTP client. It provides an easy way to make get, post, put, patch, and delete requests using the HTTP Client:

use Illuminate\Support\Facades\Http;

$response = Http::get('http://test.com');
$response = Http::post('http://test.com');
$response = Http::put('http://test.com');
$response = Http::patch('http://test.com');
$response = Http::delete('http://test.com');

You can manage responses using the set of methods provided by the Illuminate\Http\Client\Response instance returned.

$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

Please note that you will, of course, need to install Guzzle like so:

composer require guzzlehttp/guzzle

There are a lot more helpful features built-in and you can find out more about these set of the feature here: https://laravel.com/docs/7.x/http-client

This is definitely now the easiest way to make external API calls within Laravel.

What is the meaning of polyfills in HTML5?

Here are some high level thoughts and info that might help, aside from the other answers.

Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.

It kind of depends on the requirements of what your app/website needs to be compatible with.

You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/

Google Map API - Removing Markers

According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/

   function setMapOnAll(map1) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map1);
    }
  }

Next create another function to take away all these markers

 function clearMarker(){
setMapOnAll(null);
}

Then create this final function to erase all the markers when ever this function is called upon.

 function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to

}

Hope that helped good luck

What does upstream mean in nginx?

If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.

window.open with target "_blank" in Chrome

It's a setting in chrome. You can't control how the browser interprets the target _blank.

How to preview an image before and after upload?

Try this: (For Preview)

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<body>
    <form id="form1" runat="server">
        <input type="file" onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Working Demo here>

Python: Split a list into sub-lists based on index ranges

list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]

How do I give text or an image a transparent background using CSS?

The easiest method would be to use a semi-transparent background PNG image.

You can use JavaScript to make it work in Internet Explorer 6 if you need to.

I use the method outlined in Transparent PNGs in Internet Explorer 6.

Other than that, you could fake it using two side-by-side sibling elements - make one semi-transparent, then absolutely position the other over the top.

Is there a standard sign function (signum, sgn) in C/C++?

Why use ternary operators and if-else when you can simply do this

#define sgn(x) x==0 ? 0 : x/abs(x)

How to clear/remove observable bindings in Knockout.js?

I think it might be better to keep the binding the entire time, and simply update the data associated with it. I ran into this issue, and found that just calling using the .resetAll() method on the array in which I was keeping my data was the most effective way to do this.

Basically you can start with some global var which contains data to be rendered via the ViewModel:

var myLiveData = ko.observableArray();

It took me a while to realize I couldn't just make myLiveData a normal array -- the ko.oberservableArray part was important.

Then you can go ahead and do whatever you want to myLiveData. For instance, make a $.getJSON call:

$.getJSON("http://foo.bar/data.json?callback=?", function(data) {
    myLiveData.removeAll();
    /* parse the JSON data however you want, get it into myLiveData, as below */
    myLiveData.push(data[0].foo);
    myLiveData.push(data[4].bar);
});

Once you've done this, you can go ahead and apply bindings using your ViewModel as usual:

function MyViewModel() {
    var self = this;
    self.myData = myLiveData;
};
ko.applyBindings(new MyViewModel());

Then in the HTML just use myData as you normally would.

This way, you can just muck with myLiveData from whichever function. For instance, if you want to update every few seconds, just wrap that $.getJSON line in a function and call setInterval on it. You'll never need to remove the binding as long as you remember to keep the myLiveData.removeAll(); line in.

Unless your data is really huge, user's won't even be able to notice the time in between resetting the array and then adding the most-current data back in.

Subtracting 2 lists in Python

arr1=[1,2,3]
arr2=[2,1,3]
ls=[arr2-arr1 for arr1,arr2 in zip(arr1,arr2)]
print(ls)
>>[1,-1,0]

Convert UTC Epoch to local date

It's easy, new Date() just takes milliseconds, e.g.

new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)

How to delete an SVN project from SVN repository

It's easy to believe that deleting the whole Subversion repository requires "informing" Subversion that you're going to delete the repository. But Subversion only cares about managing a repository once it's created, not whether the repository exists or not ( if that makes sense ). It goes like this: the Subversion tools and commands are not adversely affected by just deleting your repository directory with the regular operating system utilities (like rm -R). A repository directory is not the same thing as an installed program directory, where deleting a program without uninstalling it might leave behind erratic config files or other dependencies. A repository is 100% self-contained in its directory, and deleting it is harmless (besides losing your project history). You just clean the slate to create a new Subversion repository and import your next project.

WorksheetFunction.CountA - not working post upgrade to Office 2010

This code works for me:

Sub test()
    Dim myRange As Range
    Dim NumRows As Integer

    Set myRange = Range("A:A")
    NumRows = Application.WorksheetFunction.CountA(myRange)

    MsgBox NumRows
End Sub

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

You can achieve what you want by using @RequestParam. For this you should do the following:

  1. Declare the RequestParams parameters that represent your objects and set the required option to false if you want to be able to send a null value.
  2. On the frontend, stringify the objects that you want to send and include them as request parameters.
  3. On the backend turn the JSON strings back into the objects they represent using Jackson ObjectMapper or something like that, and voila!

I know, its a bit of a hack but it works! ;)

Python: Get relative path from comparing two absolute paths

os.path.commonprefix() and os.path.relpath() are your friends:

>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var'])  # No common prefix: the root is the common prefix
'/'

You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:

paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
    …

You can then find the relative paths:

relative_paths = [os.path.relpath(path, common_prefix) for path in paths]

You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.

PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().

PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:

>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'

even though /usr/var is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix() solves this (specific) problem.

PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?

PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()), taking the intersection of all these parent sets, and selecting the longest common prefix.

PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath(), which returns a valid path.

CSS '>' selector; what is it?

It declares parent reference, look at this page for definition:

http://www.w3.org/TR/CSS2/selector.html#child-selectors

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

How to find numbers from a string?

Expanding on brettdj's answer, in order to parse disjoint embedded digits into separate numbers:

Sub TestNumList()
    Dim NumList As Variant  'Array

    NumList = GetNums("34d1fgd43g1 dg5d999gdg2076")

    Dim i As Integer
    For i = LBound(NumList) To UBound(NumList)
        MsgBox i + 1 & ": " & NumList(i)
    Next i
End Sub

Function GetNums(ByVal strIn As String) As Variant  'Array of numeric strings
    Dim RegExpObj As Object
    Dim NumStr As String

    Set RegExpObj = CreateObject("vbscript.regexp")
    With RegExpObj
        .Global = True
        .Pattern = "[^\d]+"
        NumStr = .Replace(strIn, " ")
    End With

    GetNums = Split(Trim(NumStr), " ")
End Function

Video auto play is not working in Safari and Chrome desktop browser

Chrome does not allow to auto play video with sound on, so make sure to add muted attribute to the video tag like this

<video width="320" height="240"  autoplay muted>
  <source src="video.mp4" type="video/mp4">
</video>

Deleting records before a certain date

This is another example using defined column/table names.

DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';

Best practice: PHP Magic Methods __set and __get

Second code example is much more proper way to do this because you are taking full control of data which are given to class. There are cases in which the __set and __get are useful but not in this case.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

Here is another solution if you want to include different browsers in on file. If you and Mac user, from sublime menu go to, Tools > New Plugin. Delete the generated code and past the following:

import sublime, sublime_plugin
import webbrowser


class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self,edit,keyPressed):
      url = self.view.file_name()
      if keyPressed == "1":
         navegator = webbrowser.get("open -a /Applications/Firefox.app %s")
      if keyPressed == "2":
         navegator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
      if keyPressed == "3":
         navegator = webbrowser.get("open -a /Applications/Safari.app %s")
      navegator.open_new(url)

Save. Then open up User Keybindings. (Tools > Command Palette > "User Key bindings"), and add this somewhere to the list:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3"}}

Now open any html file in Sublime and use one of the keybindings, which it would open that file in your favourite browser.

If Else If In a Sql Server Function

ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
    RETURNS nvarchar(3)
AS BEGIN 

    DECLARE @Final nvarchar(3)
    SELECT @Final = CASE 
        WHEN yes_ans > no_ans  AND yes_ans > na_ans THEN 'Yes'
        WHEN no_ans  > yes_ans AND no_ans  > na_ans THEN 'No'
        WHEN na_ans  > yes_ans AND na_ans  > no_ans THEN 'N/A' END
    FROM dbo.qrc_maintally
    WHERE school_id = @SchoolId

Return @Final
End

As you can see, this simplifies the code a lot. It also makes other errors in your code more obvious: you're returning an nvarchar, but declared the function to return an int (corrected in the code above).

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

You can try putting 'Access-Control-Allow-Origin':'*' in response.writeHead(, {[here]}).

How to include a Font Awesome icon in React's render()

If you are new to React JS and using create-react-app cli command to create the application, then run the following NPM command to include the latest version of font-awesome.

npm install --save font-awesome

import font-awesome to your index.js file. Just add below line to your index.js file

import '../node_modules/font-awesome/css/font-awesome.min.css'; 

or

import 'font-awesome/css/font-awesome.min.css';

Don't forget to use className as attribute

 render: function() {
    return <div><i className="fa fa-spinner fa-spin">no spinner but why</i></div>;
}

How to write data to a JSON file using Javascript

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

ImportError: No module named _ssl

Did you build the Python from source? If so, you need the --with-ssl option while building.

Good beginners tutorial to socket.io?

A 'fun' way to learn socket.io is to play BrowserQuest by mozilla and look at its source code :-)

http://browserquest.mozilla.org/

https://github.com/mozilla/BrowserQuest

Redirect echo output in shell script to logfile

You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:

{
  command1
  command2
  command3
  command4
} > file1
{
  command5
  command6
  command7
  command8
} > file2

.htaccess redirect http to https

I use the following to successfully redirect all pages of my domain from http to https:

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

Note this will redirect using the 301 'permanently moved' redirect, which will help transfer your SEO rankings.

To redirect using the 302 'temporarily moved' change [R=302,L]

How to create a self-signed certificate for a domain name for development?

Another easy way to generate a self signed certificate is to use Jexus Manager,

Jexus Manager

  1. Choose a server node in the Connections panel.
  2. In the middle panel, click Server Certificates icon to open the management page.
  3. Under Actions panel, click “Generate Self-Signed Certificate...” menu item.

https://www.jexusmanager.com/en/latest/tutorials/self-signed.html

Update row with data from another row in the same table

Here's my go:

UPDATE test as t1 
    INNER JOIN test as t2 ON 
        t1.NAME = t2.NAME AND 
        t2.value IS NOT NULL 
SET t1.VALUE = t2.VALUE;

EDIT: Removed superfluous t1.id != t2.id condition.

How to create a link to another PHP page

Easiest:

<a href="page2.php">Link</a>

And if you need to pass a value:

<a href="page2.php?val=1">Link that pass the value 1</a>

To retrive the value put in page2.php this code:

<?php
$val = $_GET["val"];
?>

Now the variable $val has the value 1.

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

Command to find information about CPUs on a UNIX machine

Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.

On SPARC at least, you have psrinfo to show you processor information, which run on its own will show you the number of CPUs the machine sees. psrinfo -p shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.

prtdiag will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Saving response from Requests to file

You can use the response.text to write to a file:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

It can also happen when you are having OneToMany relation and you try to add the child entity to the list in parent entity, then retrieve this list through parent entity (before saving this parent entity), without saving child entity itself, e.g.:

Child childEntity = new Child();
parentEntity.addChild(childEntity);
parentEntity.getChildren(); // I needed the retrieval for logging, but one may need it for other reasons.
parentRepository.save(parentEntity);

The error was thrown when I saved the parent entity. If I removed the retrieval in the previous row, then the error was not thrown, but of course that's not the solution.

The solution was saving the childEntity and adding that saved child entity to the parent entity, like this:

Child childEntity = new Child();
Child savedChildEntity = childRepository.save(childEntity);
parentEntity.addChild(savedChildEntity);
parentEntity.getChildren();
parentRepository.save(parentEntity);

using href links inside <option> tag

The accepted solution looks good, but there is one case it cannot handle:

The "onchange" event will not be triggered when the same option is reselected. So, I came up with the following improvement:

HTML

<select id="sampleSelect" >
  <option value="Home.php">Home</option>
  <option value="Contact.php">Contact</option>
  <option value="Sitemap.php">Sitemap</option>
</select>

jQuery

$("select").click(function() {
  var open = $(this).data("isopen");
  if(open) {
    window.location.href = $(this).val()
  }
  //set isopen to opposite so next time when use clicked select box
  //it wont trigger this event
  $(this).data("isopen", !open);
});

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

This error happens when you have a __unicode__ method that is a returning a field that is not entered. Any blank field is None and Python cannot convert None, so you get the error.

In your case, the problem most likely is with the PCE model's __unicode__ method, specifically the field its returning.

You can prevent this by returning a default value:

def __unicode__(self):
   return self.some_field or u'None'

RegEx to exclude a specific string constant

You could use negative lookahead, or something like this:

^([^A]|A([^B]|B([^C]|$)|$)|$).*$

Maybe it could be simplified a bit.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

You can use .on() to capture multiple events and then test for touch on the screen, e.g.:

$('#selector')
.on('touchstart mousedown', function(e){
  e.preventDefault();
  var touch = e.touches[0];
  if(touch){
    // Do some stuff
  }
  else {
    // Do some other stuff
  }
});

Breaking out of a nested loop

I remember from my student days that it was said it's mathematically provable that you can do anything in code without a goto (i.e. there is no situation where goto is the only answer). So, I never use goto's (just my personal preference, not suggesting that i'm right or wrong)

Anyways, to break out of nested loops I do something like this:

var isDone = false;
for (var x in collectionX) {
    for (var y in collectionY) {
        for (var z in collectionZ) {
            if (conditionMet) {
                // some code
                isDone = true;
            }
            if (isDone)
                break;
        }
        if (isDone) 
            break;
    }
    if (isDone)
        break;
}

... i hope that helps for those who like me are anti-goto "fanboys" :)

Setting the value of checkbox to true or false with jQuery

Try this:

HTML:

<input type="checkbox" value="FALSE" />

jQ:

$("input[type='checkbox']").on('change', function(){
  $(this).val(this.checked ? "TRUE" : "FALSE");
})

jsfiddle

Please bear in mind that unchecked checkbox will not be submitted in regular form, and you should use hidden filed in order to do it.

Best practice to validate null and empty collection in Java

We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.

Check on List or set type of collection Objects.

CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);

Check on Map type of Objects.

MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);

The return type of all methods is boolean.

How do I set the timeout for a JAX-WS webservice client?

the easiest way to avoid slow retrieval of the remote WSDL when you instantiate your SEI is to not retrieve the WSDL from the remote service endpoint at runtime.

this means that you have to update your local WSDL copy any time the service provider makes an impacting change, but it also means that you have to update your local copy any time the service provider makes an impacting change.

When I generate my client stubs, I tell the JAX-WS runtime to annotate the SEI in such a way that it will read the WSDL from a pre-determined location on the classpath. by default the location is relative to the package location of the Service SEI


<wsimport
    sourcedestdir="${dao.helter.dir}/build/generated"
    destdir="${dao.helter.dir}/build/bin/generated"
    wsdl="${dao.helter.dir}/src/resources/schema/helter/helterHttpServices.wsdl"
    wsdlLocation="./wsdl/helterHttpServices.wsdl"
    package="com.helter.esp.dao.helter.jaxws"
    >
    <binding dir="${dao.helter.dir}/src/resources/schema/helter" includes="*.xsd"/>
</wsimport>
<copy todir="${dao.helter.dir}/build/bin/generated/com/helter/esp/dao/helter/jaxws/wsdl">
    <fileset dir="${dao.helter.dir}/src/resources/schema/helter" includes="*" />
</copy>

the wsldLocation attribute tells the SEI where is can find the WSDL, and the copy makes sure that the wsdl (and supporting xsd.. etc..) is in the correct location.

since the location is relative to the SEI's package location, we create a new sub-package (directory) called wsdl, and copy all the wsdl artifacts there.

all you have to do at this point is make sure you include all *.wsdl, *.xsd in addition to all *.class when you create your client-stub artifact jar file.

(in case your curious, the @webserviceClient annotation is where this wsdl location is actually set in the java code

@WebServiceClient(name = "httpServices", targetNamespace = "http://www.helter.com/schema/helter/httpServices", wsdlLocation = "./wsdl/helterHttpServices.wsdl")

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can simply do some kind of ajax response filter for incomming responses with $.ajaxSetup. If the response contains MVC redirection you can evaluate this expression on JS side. Example code for JS below:

$.ajaxSetup({
    dataFilter: function (data, type) {
        if (data && typeof data == "string") {
            if (data.indexOf('window.location') > -1) {
                eval(data);
            }
        }
        return data;
    }
});

If data is: "window.location = '/Acount/Login'" above filter will catch that and evaluate to make the redirection.

Android design support library for API 28 (P) not working

Android documentation is clear on this.Go to the below page.Underneath,there are two columns with names "OLD BUILD ARTIFACT" and "AndroidX build artifact"

https://developer.android.com/jetpack/androidx/migrate

Now you have many dependencies in gradle.Just match those with Androidx build artifacts and replace them in the gradle.

That won't be enough.

Go to your MainActivity (repeat this for all activities) and remove the word AppCompact Activity in the statement "public class MainActivity extends AppCompatActivity " and write the same word again.But this time androidx library gets imported.Until now appcompact support file got imported and used (also, remove that appcompact import statement).

Also,go to your layout file. Suppose you have a constraint layout,then you can notice that the first line constraint layout in xml file have something related to appcompact.So just delete it and write Constraint layout again.But now androidx related constraint layout gets added.

repeat this for as many activities and as many xml layout files..

But don't worry: Android Studio displays all such possible errors while compiling.

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

Search in your web.config or App.Config if you have some tags that are not used in your project or you don't have in your references.

How add "or" in switch statements?

The example for switch statement shows that you can't stack non-empty cases, but should use gotos:

// statements_switch.cs
using System;
class SwitchTest 
{
   public static void Main()  
   {
      Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large"); 
      Console.Write("Please enter your selection: "); 
      string s = Console.ReadLine(); 
      int n = int.Parse(s);
      int cost = 0;
      switch(n)       
      {         
         case 1:   
            cost += 25;
            break;                  
         case 2:            
            cost += 25;
            goto case 1;           
         case 3:            
            cost += 50;
            goto case 1;             
         default:            
            Console.WriteLine("Invalid selection. Please select 1, 2, or3.");            
            break;      
       }
       if (cost != 0)
          Console.WriteLine("Please insert {0} cents.", cost);
       Console.WriteLine("Thank you for your business.");
   }
}

How can I show figures separately in matplotlib?

Sure. Add an Axes using add_subplot. (Edited import.) (Edited show.)

import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()

Alternatively, use add_axes.

ax1 = f1.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(range(0,10))
ax2 = f2.add_axes([0.1,0.1,0.8,0.8])
ax2.plot(range(10,20))

Why is null an object and what's the difference between null and undefined?

First part of the question:

Why is null considered an object in JavaScript?

It is a JavaScript design error they can't fix now. It should have been type null, not type object, or not have it at all. It necessitates an extra check (sometimes forgotten) when detecting real objects and is source of bugs.

Second part of the question:

Is checking


if (object == null)
Do something

the same as

if (!object)
Do something

The two checks are always both false except for:

  • object is undefined or null: both true.

  • object is primitive, and 0, "", or false: first check false, second true.

If the object is not a primitive, but a real Object, like new Number(0), new String(""), or new Boolean(false), then both checks are false.

So if 'object' is interpreted to mean a real Object then both checks are always the same. If primitives are allowed then the checks are different for 0, "", and false.

In cases like object==null, the unobvious results could be a source of bugs. Use of == is not recommended ever, use === instead.

Third part of the question:

And also:

What is the difference between null and undefined?

In JavaScript, one difference is that null is of type object and undefined is of type undefined.

In JavaScript, null==undefined is true, and considered equal if type is ignored. Why they decided that, but 0, "" and false aren't equal, I don't know. It seems to be an arbitrary opinion.

In JavaScript, null===undefined is not true since the type must be the same in ===.

In reality, null and undefined are identical, since they both represent non-existence. So do 0, and "" for that matter too, and maybe the empty containers [] and {}. So many types of the same nothing are a recipe for bugs. One type or none at all is better. I would try to use as few as possible.

'false', 'true', and '!' are another bag of worms that could be simplified, for example, if(!x) and if(x) alone are sufficient, you don't need true and false.

A declared var x is type undefined if no value is given, but it should be the same as if x was never declared at all. Another bug source is an empty nothing container. So it is best to declare and define it together, like var x=1.

People are going round and round in circles trying to figure out all these various types of nothing, but it's all just the same thing in complicated different clothes. The reality is

undefined===undeclared===null===0===""===[]==={}===nothing

And maybe all should throw exceptions.

Angular, Http GET with parameter?

An easy and usable way to solve this problem

getGetSuppor(filter): Observale<any[]> {
   return this.https.get<any[]>('/api/callCenter/getSupport' + '?' + this.toQueryString(filter));
}

private toQueryString(query): string {
   var parts = [];
   for (var property in query) {
     var value = query[propery];
     if (value != null && value != undefined)
        parts.push(encodeURIComponent(propery) + '=' + encodeURIComponent(value))
   }
   
   return parts.join('&');
}

How can I run Tensorboard on a remote server?

Here is what I do to avoid the issues of making the remote server accept your local external IP:

  • when I ssh into the machine, I use the option -L to transfer the port 6006 of the remote server into the port 16006 of my machine (for instance): ssh -L 16006:127.0.0.1:6006 olivier@my_server_ip

What it does is that everything on the port 6006 of the server (in 127.0.0.1:6006) will be forwarded to my machine on the port 16006.


  • You can then launch tensorboard on the remote machine using a standard tensorboard --logdir log with the default 6006port
  • On your local machine, go to http://127.0.0.1:16006 and enjoy your remote TensorBoard.

How do I view events fired on an element in Chrome DevTools?

Visual Event is a nice little bookmarklet that you can use to view an element's event handlers. On online demo can be viewed here.

Get name of property as a string

With C# 6.0, this is now a non-issue as you can do:

nameof(SomeProperty)

This expression is resolved at compile-time to "SomeProperty".

MSDN documentation of nameof.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it. There is no README.md file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.
https://github.com/mahmalsami/migrate-github-gitlab/blob/master/migrate.sh

What does "Object reference not set to an instance of an object" mean?

Another easy way to get this:

 Person myPet = GetPersonFromDatabase();
 // check for myPet == null... AND for myPet.PetType == null
 if ( myPet.PetType == "cat" ) <--- fall down go boom!

Characters allowed in a URL

RFC3986 defines two sets of characters you can use in a URI:

  • Reserved Characters: :/?#[]@!$&'()*+,;=

    reserved = gen-delims / sub-delims

    gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"

    sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

    The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI. URIs that differ in the replacement of a reserved character with its corresponding percent-encoded octet are not equivalent.

  • Unreserved Characters: A-Za-z0-9-_.~

    unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

    Characters that are allowed in a URI but do not have a reserved purpose are called unreserved.

Android: How to rotate a bitmap on a center point

I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.

This is the method for rotating the Matrix:

this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 

(this.getCenterX() is basically the bitmaps X position + the bitmaps width / 2)

And the method for Drawing the bitmap (called via a RenderManager Class):

canvas.drawBitmap(this.bitmap, this.matrix, null);

So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate followed by postTranslate. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/

Anyways, thanks for your help!

Internal and external fragmentation

External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.

External fragmentation

Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.

Internal fragmentation

Getting the inputstream from a classpath resource (XML file)

I tried proposed solution and forward slash in the file name did not work for me, example: ...().getResourceAsStream("/my.properties"); null was returned

Removing the slash worked: ....getResourceAsStream("my.properties");

Here is from doc API: Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:

    modified_package_name/name 

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e'). 

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

How to bind to a PasswordBox in MVVM

you can do it with attached property, see it.. PasswordBox with MVVM

Split column at delimiter in data frame

Combining @Ramnath and @Tommy's answers allowed me to find an approach that works in base R for one or more columns.

Basic usage:

> df = data.frame(
+   id=1:3, foo=c('a|b','b|c','c|d'), 
+   bar=c('p|q', 'r|s', 's|t'), stringsAsFactors=F)
> transform(df, test=do.call(rbind, strsplit(foo, '|', fixed=TRUE)), stringsAsFactors=F)
  id foo bar test.1 test.2
1  1 a|b p|q      a      b
2  2 b|c r|s      b      c
3  3 c|d s|t      c      d

Multiple columns:

> transform(df, lapply(list(foo,bar),
+ function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar X1 X2 X1.1 X2.1
1  1 a|b p|q  a  b    p    q
2  2 b|c r|s  b  c    r    s
3  3 c|d s|t  c  d    s    t

Better naming of multiple split columns:

> transform(df, lapply({l<-list(foo,bar);names(l)=c('foo','bar');l}, 
+                          function(x)do.call(rbind, strsplit(x, '|', fixed=TRUE))), stringsAsFactors=F)
  id foo bar foo.1 foo.2 bar.1 bar.2
1  1 a|b p|q     a     b     p     q
2  2 b|c r|s     b     c     r     s
3  3 c|d s|t     c     d     s     t

Difference between Apache CXF and Axis

As per my experience CXF is good in terms of configuring it into Spring environment. Also the generated classes are simple to understand. And as it is more active, we get better support in comparison to AXIS or AXIS2.

Angular-Material DateTime Picker Component?

I recommend you to checkout @angular-material-components/datetime-picker. This is a DatetimePicker like @angular/material Datepicker by adding support for choosing time.

enter image description here

Swift: Reload a View Controller

Whatever code you are writing in viewDidLoad, Add that in viewWillappear(). This will solve your problem.

How to display svg icons(.svg files) in UI using React Component?

If you use create-react-app 2.0 you can now do do it like this:

import { ReactComponent as YourSvg } from './your-svg.svg';

And then use it just like you would normally use a component:

const App = () => (
 <div>
   <YourSvg />
 </div>
);

pgadmin4 : postgresql application server could not be contacted.

I had the same issue on Windows 10, with a new installation of PostgreSQL 10.

I solved it by including the path C:\PostgreSQL\10\bin ({your path to postgresql}\bin) to system environment variables.

To access environment variables: Control Panel > System and security > System or right click on PC, then > Advance system settings > Environment variables > System variables > Path > Edit.

Static way to get 'Context' in Android?

I think you need a body for the getAppContext() method:

public static Context getAppContext()
   return MyApplication.context; 

Django set field value after a form is initialized

If you want to do it within the form's __init__ method for some reason, you can manipulate the initial dict:

class MyForm(forms.Form):
    my_field = forms.CharField(max_length=255)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.initial['my_field'] = 'Initial value'

Function overloading in Python: Missing

As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

Although an API like that sometimes indicates a design problem.

How to call an async method from a getter or setter?

When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:

string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();

You could argue that I abuse the framework, but it works.

AttributeError: 'DataFrame' object has no attribute

value_counts is a Series method rather than a DataFrame method (and you are trying to use it on a DataFrame, clean). You need to perform this on a specific column:

clean[column_name].value_counts()

It doesn't usually make sense to perform value_counts on a DataFrame, though I suppose you could apply it to every entry by flattening the underlying values array:

pd.value_counts(df.values.flatten())

How to turn off word wrapping in HTML?

You need to use the CSS white-space attribute.

In particular, white-space: nowrap and white-space: pre are the most commonly used values. The first one seems to be what you 're after.

Is there any difference between GROUP BY and DISTINCT

group by is used in aggregate operations -- like when you want to get a count of Bs broken down by column C

select C, count(B) from myTbl group by C

distinct is what it sounds like -- you get unique rows.

In sql server 2005, it looks like the query optimizer is able to optimize away the difference in the simplistic examples I ran. Dunno if you can count on that in all situations, though.

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

How do I resolve ClassNotFoundException?

Put all the code in try block then catch exception in a catch block

try
{
    // code
}
catch(ClassNotFoundException e1)
{
    e1.getmessage();
}

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

How to run or debug php on Visual Studio Code (VSCode)

There is now a handy guide for configuring PHP debugging in Visual Studio Code at http://blogs.msdn.com/b/nicktrog/archive/2016/02/11/configuring-visual-studio-code-for-php-development.aspx

From the link, the steps are:

  1. Download and install Visual Studio Code
  2. Configure PHP linting in user settings
  3. Download and install the PHP Debug extension from the Visual Studio Marketplace
  4. Configure the PHP Debug extension for XDebug

Note there are specific details in the linked article, including the PHP values for your VS Code user config, and so on.

Download Excel file via AJAX MVC

  $.ajax({
    global: false,
    url: SitePath + "/User/ExportTeamMembersInExcel",
    "data": { 'UserName': UserName, 'RoleId': RoleId, UserIds: AppraseeId },
    "type": "POST",
    "dataType": "JSON",
   "success": function (result) {
        debugger
        var bytes = new Uint8Array(result.FileContents);
        var blob = new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "myFileName.xlsx";
        link.click();
      },
    "error": function () {
        alert("error");
    }
})


[HttpPost]
    public JsonResult ExportTeamMembersInExcel(string UserName, long? RoleId, string[] UserIds)
    {
        MemoryStream stream = new MemoryStream();
        FileContentResult robj;
        DataTable data = objuserservice.ExportTeamToExcel(UserName, RoleId, UserIds);
        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(data, "TeamMembers");
            using (stream)
            {
                wb.SaveAs(stream);
            }
        }
        robj = File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "TeamMembers.xlsx");
        return Json(robj, JsonRequestBehavior.AllowGet);
    }

How to change XAMPP apache server port?

if don't work above port id then change it.like 8082,8080 Restart xammp,Start apache server,Check it.It's now working.

How to get first object out from List<Object> using Linq

You can do

Component depCountry = lstComp
                       .Select(x => x.ComponentValue("Dep"))
                       .FirstOrDefault();

Alternatively if you are wanting this for the entire dictionary of values, you can even tie it back to the key

var newDictionary = dic.Select(x => new 
            {
               Key = x.Key,
               Value = x.Value.Select( y => 
                      {
                          depCountry = y.ComponentValue("Dep")
                      }).FirstOrDefault()
             }
             .Where(x => x.Value != null)
             .ToDictionary(x => x.Key, x => x.Value());

This will give you a new dictionary. You can access the values

var myTest = newDictionary[key1].depCountry     

How can I render inline JavaScript with Jade / Pug?

Use script tag with the type specified, simply include it before the dot:

script(type="text/javascript").
  if (10 == 10) {
    alert("working");
  }

This will compile to:

<script type="text/javascript">
  if (10 == 10) {
    alert("working");
  }
</script>

swift 3.0 Data to String?

let urlString = baseURL + currency

    if let url = URL(string: urlString){
        let session = URLSession(configuration: .default)        
        let task = session.dataTask(with: url){ (data, reponse, error) in
            if error != nil{
                print(error)
                return
            }


            let dataString = String(data: data!, encoding: .utf8)
            print(dataString)

        }

        task.resume()

    }

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());


  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);

      }

in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

You probably just need to see the ASCII and EXTENDED ASCII character sets. As far as I know any of these are allowed in a char/varchar field.

If you use nchar/nvarchar then it's pretty much any character in any unicode set in the world.

enter image description here

enter image description here

How to "git clone" including submodules?

I think you can go with 3 steps:

git clone
git submodule init
git submodule update

No internet on Android emulator - why and how to fix?

If by "use internet", you mean you can not access the internet from an activity while testing on the emulator, make sure you have set the internet permission in your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 

If you are using the web browser, refer to Donal's post

Windows 7 - Add Path

I founded the problem: Just insert the folder without the executable file.
so Instead of:

C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe

you have to write this:

C:\Program Files (x86)\SumatraPDF\

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

What's the main difference between Java SE and Java EE?

Best description i've encounter so far is available on Oracle website.

Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

If you consider developing application using for example Spring Framework you will use both API's and would have to learn key concept of JavaServer Pages and related technologies like for ex.: JSP, JPA, JDBC, Dependency Injection etc.

How can I pretty-print JSON using node.js?

If you don't want to store this anywhere, but just view the object for debugging purposes.

console.log(JSON.stringify(object, null, "  "));

You can change the third parameter to adjust the indentation.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I think that you can bind the load event of the iframe, the event fires when the iframe content is fully loaded.

At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.

Code:

var iframeError;

function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout(error, 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));

});

Demo: http://jsfiddle.net/IrvinDominin/QXc6P/

Second problem

It is because you miss the parens in the inline function call; try change this:

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

into this:

<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>

Demo: http://jsfiddle.net/IrvinDominin/ALBXR/4/

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

laravel throwing MethodNotAllowedHttpException

You are getting that error because you are posting to a GET route.

I would split your routing for validate into a separate GET and POST routes.

New Routes:

Route::post('validate', 'MemberController@validateCredentials');

Route::get('validate', function () {
    return View::make('members/login');
});

Then your controller method could just be

public function validateCredentials()
{
    $email = Input::post('email');
    $password = Input::post('password');
    return "Email: " . $email . " and Password: " . $password;
}

Writing a large resultset to an Excel file using POI

Oh. I think you're writing the workbook out 944,000 times. Your wb.write(bos) call is in the inner loop. I'm not sure this is quite consistent with the semantics of the Workbook class? From what I can tell in the Javadocs of that class, that method writes out the entire workbook to the output stream specified. And it's gonna write out every row you've added so far once for every row as the thing grows.

This explains why you're seeing exactly 1 row, too. The first workbook (with one row) to be written out to the file is all that is being displayed - and then 7GB of junk thereafter.

get an element's id

Super Easy Way is

  $('.CheckBxMSG').each(function () {
            var ChkBxMsgId;
            ChkBxMsgId = $(this).attr('id');
            alert(ChkBxMsgId);
        });

Tell me if this helps

Best way to "negate" an instanceof

ok just my two cents, use a is string method:

public static boolean isString(Object thing) {
    return thing instanceof String;
}

public void someMethod(Object thing){
    if (!isString(thing)) {
        return null;
    }
    log.debug("my thing is valid");
}

Difference between break and continue statement

continue skips the current executing loop and MOVES TO the next loop whereas break MOVES OUT of the loop and executes the next statement after the loop. I learned the difference using the following code. Check out the different outputs.Hope this helps.

public static void main(String[] args) {
    for(int i = 0; i < 5; i++){
        if (i == 3) {
            continue;
        }
        System.out.print(i);
    }
}//prints out 0124, continue moves to the next iteration skipping printing 3

public static void main(String[] args) {
    for(int i = 0; i < 5; i++){
        if (i == 3) {
            break;
        }
        System.out.print(i);
    }
}//prints out 012, break moves out of the loop hence doesnt print 3 and 4

How to install pip with Python 3?

What’s New In Python 3.4

...

pip should always be available

...

By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.

https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453

so if you have python 3.4 installed, you can just: sudo pip3 install xxx

How to draw polygons on an HTML5 canvas?

Create a path with moveTo and lineTo (live demo):

var ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();

Visual Studio 2015 or 2017 does not discover unit tests

For me upgrading to version 3.7 of NUnit worked.

"A referral was returned from the server" exception when accessing AD from C#

This is the answer for the question.Reason for the cause is my LDAP string was wrong.

    try
    {
        string adServer = ConfigurationManager.AppSettings["Server"];
        string adDomain = ConfigurationManager.AppSettings["Domain"];
        string adUsername = ConfigurationManager.AppSettings["AdiminUsername"];
        string password = ConfigurationManager.AppSettings["Password"];
        string[] dc = adDomain.Split('.');
        string dcAdDomain = string.Empty;

        foreach (string item in dc)
        {
            if (dc[dc.Length - 1].Equals(item))
                dcAdDomain = dcAdDomain + "DC=" + item;
            else
                dcAdDomain = dcAdDomain + "DC=" + item + ",";
        }

        DirectoryEntry de = new DirectoryEntry("LDAP://" + adServer + "/CN=Users," + dcAdDomain, adUsername, password);

        DirectorySearcher ds = new DirectorySearcher(de);

        ds.SearchScope = SearchScope.Subtree;

        ds.Filter = "(&(objectClass=User)(sAMAccountName=" + username + "))";

        if (ds.FindOne() != null)
            return true;
    }
    catch (Exception ex)
    {
        ExLog(ex);
    }
    return false;

jQuery UI Accordion Expand/Collapse All

Here's the code by Sinetheta converted to a jQuery plugin: Save below code to a js file.

$.fn.collapsible = function() {
    $(this).addClass("ui-accordion ui-widget ui-helper-reset");
    var headers = $(this).children("h3");
    headers.addClass("accordion-header ui-accordion-header ui-helper-reset ui-state-active ui-accordion-icons ui-corner-all");
    headers.append('<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s">');
    headers.click(function() {
        var header = $(this);
        var panel = $(this).next();
        var isOpen = panel.is(":visible");
        if(isOpen)  {
            panel.slideUp("fast", function() {
                panel.hide();
                header.removeClass("ui-state-active")
                    .addClass("ui-state-default")
                    .children("span").removeClass("ui-icon-triangle-1-s")
                        .addClass("ui-icon-triangle-1-e");
          });
        }
        else {
            panel.slideDown("fast", function() {
                panel.show();
                header.removeClass("ui-state-default")
                    .addClass("ui-state-active")
                    .children("span").removeClass("ui-icon-triangle-1-e")
                        .addClass("ui-icon-triangle-1-s");
          });
        }
    });
}; 

Refer it in your UI page and call similar to jQuery accordian call:

$("#accordion").collapsible(); 

Looks cleaner and avoids any classes to be added to the markup.

Read and Write CSV files including unicode with Python 2.7

I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:

class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
    # Redirect output to a queue
    self.queue = StringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
    self.stream = f

    # Force BOM
    if encoding=="utf-16":
        import codecs
        f.write(codecs.BOM_UTF16)

    self.encoding = encoding

def writerow(self, row):
    # Modified from original: now using unicode(s) to deal with e.g. ints
    self.writer.writerow([unicode(s).encode("utf-8") for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = data.encode(self.encoding)

    # strip BOM
    if self.encoding == "utf-16":
        data = data[2:]

    # write to the target stream
    self.stream.write(data)
    # empty queue
    self.queue.truncate(0)

def writerows(self, rows):
    for row in rows:
        self.writerow(row)

Creating a PDF from a RDLC Report in the Background

You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:

var lr = new LocalReport
{
    ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
    EnableExternalImages = true
};

lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));

string mimeType, encoding, extension;

Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
    (
        "PDF",
        @"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
        out mimeType,
        out encoding,
        out extension,
        out streams,
        out warnings
    );

var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));

var idx = 0;
while (File.Exists(saveAs))
{
    idx++;
    saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}

using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
    stream.Write(renderedBytes, 0, renderedBytes.Length);
    stream.Close();
}

lr.Dispose();

You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.

What is an NP-complete in computer science?

NP-Complete means something very specific and you have to be careful or you will get the definition wrong. First, an NP problem is a yes/no problem such that

  1. There is polynomial-time proof for every instance of the problem with a "yes" answer that the answer is "yes", or (equivalently)
  2. There exists a polynomial-time algorithm (possibly using random variables) that has a non-zero probability of answering "yes" if the answer to an instance of the problem is "yes" and will say "no" 100% of the time if the answer is "no." In other words, the algorithm must have a false-negative rate less than 100% and no false positives.

A problem X is NP-Complete if

  1. X is in NP, and
  2. For any problem Y in NP, there is a "reduction" from Y to X: a polynomial-time algorithm that transforms any instance of Y into an instance of X such that the answer to the Y-instance is "yes" if and only if the answer X-instance is "yes".

If X is NP-complete and a deterministic, polynomial-time algorithm exists that can solve all instances of X correctly (0% false-positives, 0% false-negatives), then any problem in NP can be solved in deterministic-polynomial-time (by reduction to X).

So far, nobody has come up with such a deterministic polynomial-time algorithm, but nobody has proven one doesn't exist (there's a million bucks for anyone who can do either: the is the P = NP problem). That doesn't mean that you can't solve a particular instance of an NP-Complete (or NP-Hard) problem. It just means you can't have something that will work reliably on all instances of a problem the same way you could reliably sort a list of integers. You might very well be able to come up with an algorithm that will work very well on all practical instances of a NP-Hard problem.

JavaScript and getElementById for multiple elements with the same ID

As others have stated, you shouldn't have the same ID more than once in your HTML, however... elements with an ID are attached to the document object and to window on Internet Explorer. Refer to:

Do DOM tree elements with ids become global variables?

If more than one element with the same ID exists in your HTML, this property is attached as an array. I'm sorry, but I don't know where to look if this is the standard behavior or at least you get the same behavior between browsers, which I doubt.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

The LIBXML_NOCDATA is optional third parameter of simplexml_load_file() function. This returns the XML object with all the CDATA data converted into strings.

$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);
echo "<pre>";
print_r($xml);
echo "</pre>";


Fix CDATA in SimpleXML

Python append() vs. + operator on lists, why do these give different results?

Python lists are heterogeneous that is the elements in the same list can be any type of object. The expression: c.append(c) appends the object c what ever it may be to the list. In the case it makes the list itself a member of the list.

The expression c += c adds two lists together and assigns the result to the variable c. The overloaded + operator is defined on lists to create a new list whose contents are the elements in the first list and the elements in the second list.

So these are really just different expressions used to do different things by design.

Converting XML to JSON using Python?

This stuff here is actively maintained and so far is my favorite: xml2json in python

How to use HTTP_X_FORWARDED_FOR properly?

If you use it in a database, this is a good way:

Set the ip field in database to varchar(250), and then use this:

$theip = $_SERVER["REMOTE_ADDR"];

if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    $theip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')';
}

if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
    $theip .= '('.$_SERVER["HTTP_CLIENT_IP"].')';
}

$realip = substr($theip, 0, 250);

Then you just check $realip against the database ip field

Customize UITableView header section

Swift version of Lochana Tejas answer:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18))
    let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18))
    label.font = UIFont.systemFontOfSize(14)
    label.text = list.objectAtIndex(indexPath.row) as! String
    view.addSubview(label)
    view.backgroundColor = UIColor.grayColor() // Set your background color

    return view
}

What is use of c_str function In c++

c_str returns a const char* that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string.

For example, consider this code:

std::string str("Hello world!");
int pos1 = str.find_first_of('w');

int pos2 = strchr(str.c_str(), 'w') - str.c_str();

if (pos1 == pos2) {
    printf("Both ways give the same result.\n");
}

See it in action.

Notes:

¹ This is not entirely true because an std::string (unlike a C string) can contain the \0 character. If it does, the code that receives the return value of c_str() will be fooled into thinking that the string is shorter than it really is, since it will interpret \0 as the end of the string.

adding .css file to ejs

app.use(express.static(__dirname + '/public'));
<link href="/css/style.css" rel="stylesheet" type="text/css">

So folder structure should be:

.
./app.js
./public
 /css
 /style.css

How to rename a table in SQL Server?

Nothing worked from proposed here .. So just pored the data into new table

SELECT * 
INTO [acecodetable].['PSCLineReason']
FROM [acecodetable].['15_PSCLineReason'];

maybe will be useful for someone..

In my case it didn't recognize the new schema also the dbo was the owner..

UPDATE

EXECUTE sp_rename N'[acecodetable].[''TradeAgreementClaim'']', N'TradeAgreementClaim';

Worked for me. I found it from the script generated automatically when updating the PK for one of the tables. This way it recognized the new schema as well..

SQL Server format decimal places with commas

From a related SO question: Format a number with commas but without decimals in SQL Server 2008 R2?

SELECT CONVERT(varchar, CAST(1112 AS money), 1)

This was tested in SQL Server 2008 R2.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

Make sure you have the EntityFramework Nuget package installed for your project.

From @TonyDing's answer:

Right-click on the Solution from the Visual Studio Solution Explorer click the Manage Nuget packages for solution and install the EntityFramework

Once it is installed, I still had the error, but then did a reinstall per @papergodzilla's comment:

Update-Package -reinstall

and it resolved my issue

Do this in the Package Manager Console (View > Other windows > Package Manager Console).
Now everything is good!

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Smooth scrolling when clicking an anchor link

If you have a simple button on the page to scroll down to a div and want the back button to work by jumping to top, just add this code:

$(window).on('hashchange', function(event) {
    if (event.target.location.hash=="") {
        window.scrollTo(0,0);
    }
});

This could be extended to jump to different divs too, by reading the hash value, and scrolling like Joseph Silbers answer.

Can I add background color only for padding?

This would be a proper CSS solution which works for IE8/9 as well (IE8 with html5shiv ofcourse): codepen

nav {
  margin:0px auto;
  height:50px;
  background-color:gray;
  padding:10px;
  border:2px solid red;
  position: relative;
  color: white;
  z-index: 1;
}

nav:after {
  content: '';
  background: black;
  display: block;
  position: absolute;
  margin: 10px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: -1;
}

Angular 1 - get current URL parameters

In your route configuration you typically define a route like,

.when('somewhere/:param1/:param2')

You can then either get the route in the resolve object by using $route.current.params or in a controller, $routeParams. In either case the parameters is extracted using the mapping of the route, so param1 can be accessed by $routeParams.param1 in the controller.

Edit: Also note that the mapping has to be exact

/some/folder/:param1

Will only match a single parameter.

/some/folder/:param1/:param2 

Will only match two parameters.

This is a bit different then most dynamic server side routes. For example NodeJS (Express) route mapping where you can supply only a single route with X number of parameters.

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

How do I get my C# program to sleep for 50 msec?

For readability:

using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));

Replace all occurrences of a string in a data frame

If you are only looking to replace all occurrences of "< " (with space) with "<" (no space), then you can do an lapply over the data frame, with a gsub for replacement:

> data <- data.frame(lapply(data, function(x) {
+                  gsub("< ", "<", x)
+              }))
> data
  name var1 var2
1    a   <2   <3
2    a   <2   <3
3    a   <2   <3
4    b   <2   <3
5    b   <2   <3
6    b   <2   <3
7    c   <2   <3
8    c   <2   <3
9    c   <2   <3

pandas convert some columns into rows

UPDATE
From v0.20, melt is a first order function, you can now use

df.melt(id_vars=["location", "name"], 
        var_name="Date", 
        value_name="Value")

  location    name        Date  Value
0        A  "test"    Jan-2010     12
1        B   "foo"    Jan-2010     18
2        A  "test"    Feb-2010     20
3        B   "foo"    Feb-2010     20
4        A  "test"  March-2010     30
5        B   "foo"  March-2010     25

OLD(ER) VERSIONS: <0.20

You can use pd.melt to get most of the way there, and then sort:

>>> df
  location  name  Jan-2010  Feb-2010  March-2010
0        A  test        12        20          30
1        B   foo        18        20          25
>>> df2 = pd.melt(df, id_vars=["location", "name"], 
                  var_name="Date", value_name="Value")
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
1        B   foo    Jan-2010     18
2        A  test    Feb-2010     20
3        B   foo    Feb-2010     20
4        A  test  March-2010     30
5        B   foo  March-2010     25
>>> df2 = df2.sort(["location", "name"])
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
2        A  test    Feb-2010     20
4        A  test  March-2010     30
1        B   foo    Jan-2010     18
3        B   foo    Feb-2010     20
5        B   foo  March-2010     25

(Might want to throw in a .reset_index(drop=True), just to keep the output clean.)

Note: pd.DataFrame.sort has been deprecated in favour of pd.DataFrame.sort_values.

Mockito: Inject real objects into private @Autowired fields

I know this is an old question, but we were faced with the same problem when trying to inject Strings. So we invented a JUnit5/Mockito extension that does exactly what you want: https://github.com/exabrial/mockito-object-injection

EDIT:

@InjectionMap
 private Map<String, Object> injectionMap = new HashMap<>();

 @BeforeEach
 public void beforeEach() throws Exception {
  injectionMap.put("securityEnabled", Boolean.TRUE);
 }

 @AfterEach
 public void afterEach() throws Exception {
  injectionMap.clear();
 }

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Thought I would add that we also ran into this issue with multiple machines in our domain. I created a list of offending machines and added them all to a text file from which to run the script. I ran this from the CMD prompt using elevated privileges.

 psexec @firewallFix.txt -d netsh advfirewall firewall 
        set rule name="Windows Management Instrumentation (WMI-In)" 
        profile=domain new enable=yes profile=domain

Counting duplicates in Excel

Let excel do the work.

  1. Select column
  2. Select Data tab
  3. Select Subtotal, then "count"
  4. DONE

Adds it up for you and puts total

Trinidad Count  99
    Trinidad Colorado
    Trinidad Colorado
    Trinidad Colorado
    Trinidad Colorado
    Trinidad Colorado
    Trinidad Colorado
Trinidad Colorado Count 6
    Trinidad.
    Trinidad.
Trinidad. Count 2
    winnemucca
    Winnemucca
    Winnemucca
    Winnemucca
    Winnemucca
    winnemucca
    Winnemucca
    Winnemucca
    Winnemucca
    winnemucca
    Winnemucca
    Winnemucca
    Winnemucca
    Winnemucca
winnemucca Count    14

Push to GitHub without a password using ssh-key

If it is asking you for a username and password, your origin remote is pointing at the HTTPS URL rather than the SSH URL.

Change it to ssh.

For example, a GitHub project like Git will have an HTTPS URL:

https://github.com/<Username>/<Project>.git

And the SSH one:

[email protected]:<Username>/<Project>.git

You can do:

git remote set-url origin [email protected]:<Username>/<Project>.git

to change the URL.

error: unknown type name ‘bool’

C90 does not support the boolean data type.

C99 does include it with this include:

#include <stdbool.h>

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Inline Javascript:

<button onclick="window.location='http://www.example.com';">Visit Page Now</button>

Defining a function in Javascript:

<script>
    function visitPage(){
        window.location='http://www.example.com';
    }
</script>
<button onclick="visitPage();">Visit Page Now</button>

or in Jquery

<button id="some_id">Visit Page Now</button>

$('#some_id').click(function() {
  window.location='http://www.example.com';
});

How to send and retrieve parameters using $state.go toParams and $stateParams?

If you want to pass non-URL state, then you must not use url when setting up your state. I found the answer on a PR and did some monkeying around to better understand.

$stateProvider.state('toState', {
  templateUrl:'wokka.html',
  controller:'stateController',
  params: {
    'referer': 'some default', 
    'param2': 'some default', 
    'etc': 'some default'
  }
});

Then you can navigate to it like so:

$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });

Or:

var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);

And in HTML thusly:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.

get keys of json-object in JavaScript

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

How to get current html page title with javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

How to change Label Value using javascript

Based off your code, i created this Fiddle
You need to use

var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];


if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.

How to iterate (keys, values) in JavaScript?

You can do something like this :

dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);

for(var i = 0; i < keys.length;i++){
   //keys[i] for key
   //dictionary[keys[i]] for the value
}

Linq select object from list depending on objects attribute

Answers = Answers.GroupBy(a => a.id).Select(x => x.First());

This will select each unique object by email

How do I print out the contents of an object in Rails for easy debugging?

You need to use debug(@var). It's exactly like "print_r".

Use JavaScript to place cursor at end of text in text input element

input = $('input'); 
input.focus().val(input.val()+'.'); 
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

Setting href attribute at runtime

Set the href attribute with

$(selector).attr('href', 'url_goes_here');

and read it using

$(selector).attr('href');

Where "selector" is any valid jQuery selector for your <a> element (".myClass" or "#myId" to name the most simple ones).

Hope this helps !

How to filter for multiple criteria in Excel?

The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.

http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm

Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.

  1. E1 : Letters
  2. E2 : =m
  3. E3 : =h
  4. E4 : =j

I put the data starting on row 5:

  1. A5 : Letters
  2. A6 :
  3. A7 :
  4. ...

Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.

That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.

How good is Java's UUID.randomUUID?

Does anybody have any experience to share?

There are 2^122 possible values for a type-4 UUID. (The spec says that you lose 2 bits for the type, and a further 4 bits for a version number.)

Assuming that you were to generate 1 million random UUIDs a second, the chances of a duplicate occurring in your lifetime would be vanishingly small. And to detect the duplicate, you'd have to solve the problem of comparing 1 million new UUIDs per second against all of the UUIDs you have previously generated1!

The chances that anyone has experienced (i.e. actually noticed) a duplicate in real life are even smaller than vanishingly small ... because of the practical difficulty of looking for collisions.

Now of course, you will typically be using a pseudo-random number generator, not a source of truly random numbers. But I think we can be confident that if you are using a creditable provider for your cryptographic strength random numbers, then it will be cryptographic strength, and the probability of repeats will be the same as for an ideal (non-biased) random number generator.

However, if you were to use a JVM with a "broken" crypto- random number generator, all bets are off. (And that might include some of the workarounds for "shortage of entropy" problems on some systems. Or the possibility that someone has tinkered with your JRE, either on your system or upstream.)


1 - Assuming that you used "some kind of binary btree" as proposed by an anonymous commenter, each UUID is going to need O(NlogN) bits of RAM memory to represent N distinct UUIDs assuming low density and random distribution of the bits. Now multiply that by 1,000,000 and the number of seconds that you are going to run the experiment for. I don't think that is practical for the length of time needed to test for collisions of a high quality RNG. Not even with (hypothetical) clever representations.

How to use global variables in React Native?

If you just want to pass some data from one screen to the next, you can pass them with the navigation.navigate method like this:

<Button onPress={()=> {this.props.navigation.navigate('NextScreen',{foo:bar)} />

and in 'NextScreen' you can access them with the navigation.getParam() method:

let foo=this.props.navigation.getParam(foo);

But it can get really "messy" if you have more than a couple of variables to pass..

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8, ViewChild has another param

@ViewChild('nameInput', {static: false}) component

I resolved my issue like below

@ViewChild(MatSort, {static: false}) sort: MatSort;

Visual Studio Code: Auto-refresh file changes

{
    "files.useExperimentalFileWatcher" : true
}

in Code -> Preferences -> Settings

Tested with Visual Studio Code Version 1.26.1 on mac and win

Can Mockito capture arguments of a method called multiple times?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:

import static org.mockito.Mockito.*;

In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());

List<MyExampleClass> passedArguments = argument.getAllValues();

for (MyExampleClass data : passedArguments){
    //assertSometing ...
    System.out.println(data.getFoo());
}

The list of all passed arguments during your test is accessible via the argument.getAllValues() method.

The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.

JavaScript: Parsing a string Boolean value?

I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:

var BoolHelpers = {
    tryParse: function (value) {
        if (typeof value == 'boolean' || value instanceof Boolean)
            return value;
        if (typeof value == 'string' || value instanceof String) {
            value = value.trim().toLowerCase();
            if (value === 'true' || value === 'false')
                return value === 'true';
        }
        return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
    }
}

The usage:

var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);

What is the best project structure for a Python application?

Check out Open Sourcing a Python Project the Right Way.

Let me excerpt the project layout part of that excellent article:

When setting up a project, the layout (or directory structure) is important to get right. A sensible layout means that potential contributors don't have to spend forever hunting for a piece of code; file locations are intuitive. Since we're dealing with an existing project, it means you'll probably need to move some stuff around.

Let's start at the top. Most projects have a number of top-level files (like setup.py, README.md, requirements.txt, etc). There are then three directories that every project should have:

  • A docs directory containing project documentation
  • A directory named with the project's name which stores the actual Python package
  • A test directory in one of two places
    • Under the package directory containing test code and resources
    • As a stand-alone top level directory To get a better sense of how your files should be organized, here's a simplified snapshot of the layout for one of my projects, sandman:
$ pwd
~/code/sandman
$ tree
.
|- LICENSE
|- README.md
|- TODO.md
|- docs
|   |-- conf.py
|   |-- generated
|   |-- index.rst
|   |-- installation.rst
|   |-- modules.rst
|   |-- quickstart.rst
|   |-- sandman.rst
|- requirements.txt
|- sandman
|   |-- __init__.py
|   |-- exception.py
|   |-- model.py
|   |-- sandman.py
|   |-- test
|       |-- models.py
|       |-- test_sandman.py
|- setup.py

As you can see, there are some top level files, a docs directory (generated is an empty directory where sphinx will put the generated documentation), a sandman directory, and a test directory under sandman.

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

insert data from one table to another in mysql

INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
VALUES ( 
      (SELECT magazine_subscription_id, 
              subscription_name, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC));

Overwriting txt file in java

SOLVED

My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.

File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();

File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");

String source = textArea.getText();
System.out.println(source);

try {
    FileWriter f2 = new FileWriter(fnew, false);
    f2.write(source);
    f2.close();

} catch (IOException e) {
    e.printStackTrace();
}   

Check if a column contains text using SQL

Try this:

SElECT * FROM STUDENTS WHERE LEN(CAST(STUDENTID AS VARCHAR)) > 0

With this you get the rows where STUDENTID contains text