Programs & Examples On #Qnames

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")

Difference between a User and a Login in SQL Server

In Short,

Logins will have the access of the server.

and

Users will have the access of the database.

Android textview outline text

MagicTextView is very useful to make stroke font, but in my case, it cause error like this this error caused by duplication background attributes which set by MagicTextView

so you need to edit attrs.xml and MagicTextView.java

attrs.xml

<attr name="background" format="reference|color" />
 ?
<attr name="mBackground" format="reference|color" />

MagicTextView.java 88:95

if (a.hasValue(R.styleable.MagicTextView_mBackground)) {
Drawable background = a.getDrawable(R.styleable.MagicTextView_mBackground);
if (background != null) {
    this.setBackgroundDrawable(background);
} else {
    this.setBackgroundColor(a.getColor(R.styleable.MagicTextView_mBackground, 0xff000000));
}
}

php timeout - set_time_limit(0); - don't work

ini_set('max_execution_time', 300);

use this

How to make custom error pages work in ASP.NET MVC 4

I had everything set up, but still couldn't see proper error pages for status code 500 on our staging server, despite the fact everything worked fine on local development servers.

I found this blog post from Rick Strahl that helped me.

I needed to add Response.TrySkipIisCustomErrors = true; to my custom error handling code.

When adding a Javascript library, Chrome complains about a missing source map, why?

Newer files on JsDelivr get the sourcemap added automatically to the end of them. This is fine and doesn't throw any SourceMap-related notice in the console as long as you load the files from JsDelivr. The problem occurs only when you copy then load these files from your own server. In order to fix this for locally loaded files simply remove the last line in the JS file(s) downloaded from JsDelivr. It should look something like this:

//# sourceMappingURL=/sm/64bec5fd901c75766b1ade899155ce5e1c28413a4707f0120043b96f4a3d8f80.map

As you can see it's commented out but Chrome still parses it.

Set element focus in angular way

The problem with your solution is that it does not work well when tied down to other directives that creates a new scope, e.g. ng-repeat. A better solution would be to simply create a service function that enables you to focus elements imperatively within your controllers or to focus elements declaratively in the html.

DEMO

JAVASCRIPT

Service

 .factory('focus', function($timeout, $window) {
    return function(id) {
      // timeout makes sure that it is invoked after any other event has been triggered.
      // e.g. click events that need to run before the focus or
      // inputs elements that are in a disabled state but are enabled when those events
      // are triggered.
      $timeout(function() {
        var element = $window.document.getElementById(id);
        if(element)
          element.focus();
      });
    };
  });

Directive

  .directive('eventFocus', function(focus) {
    return function(scope, elem, attr) {
      elem.on(attr.eventFocus, function() {
        focus(attr.eventFocusId);
      });

      // Removes bound events in the element itself
      // when the scope is destroyed
      scope.$on('$destroy', function() {
        elem.off(attr.eventFocus);
      });
    };
  });

Controller

.controller('Ctrl', function($scope, focus) {
    $scope.doSomething = function() {
      // do something awesome
      focus('email');
    };
  });

HTML

<input type="email" id="email" class="form-control">
<button event-focus="click" event-focus-id="email">Declarative Focus</button>
<button ng-click="doSomething()">Imperative Focus</button>

Maven is not working in Java 8 when Javadoc tags are incomplete

Added below

JAVA_TOOL_OPTIONS=-DadditionalJOption=-Xdoclint:none

Into Jenkins job :

Configuration > Build Environment > Inject environment variables to the build process > Properties Content

Solved my problem of code building through Jenkins Maven :-)

How many times a substring occurs

I will keep my accepted answer as the "simple and obvious way to do it" - however, that does not cover overlapping occurrences. Finding out those can be done naively, with multiple checking of the slices - as in: sum("GCAAAAAGH"[i:].startswith("AAA") for i in range(len("GCAAAAAGH")))

(which yields 3) - it can be done by trick use of regular expressions, as can be seen at Python regex find all overlapping matches? - and it can also make for fine code golfing - This is my "hand made" count for overlappingocurrences of patterns in a string which tries not to be extremely naive (at least it does not create new string objects at each interaction):

def find_matches_overlapping(text, pattern):
    lpat = len(pattern) - 1
    matches = []
    text = array("u", text)
    pattern = array("u", pattern)
    indexes = {}
    for i in range(len(text) - lpat):
        if text[i] == pattern[0]:
            indexes[i] = -1
        for index, counter in list(indexes.items()):
            counter += 1
            if text[i] == pattern[counter]:
                if counter == lpat:
                    matches.append(index)
                    del indexes[index]
                else:
                    indexes[index] = counter
            else:
                del indexes[index]
    return matches

def count_matches(text, pattern):
    return len(find_matches_overlapping(text, pattern))

Converting XDocument to XmlDocument and vice versa

If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:

using System.Xml; 
using System.Xml.Linq;

namespace www.dimaka.com
{ 
    internal static class LinqHelper 
    { 
        public static XmlDocument ToXmlDocument(this XDocument xDocument) 
        { 
            var xmlDocument = new XmlDocument(); 
            using (var reader = xDocument.CreateReader()) 
            { 
                xmlDocument.Load(reader); 
            }

            var xDeclaration = xDocument.Declaration; 
            if (xDeclaration != null) 
            { 
                var xmlDeclaration = xmlDocument.CreateXmlDeclaration( 
                    xDeclaration.Version, 
                    xDeclaration.Encoding, 
                    xDeclaration.Standalone);

                xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild); 
            }

            return xmlDocument; 
        } 
    } 
}

Hope that helps!

Get difference between two dates in months using Java

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.

maxlength ignored for input type="number" in Chrome

I have two ways for you do that

First: Use type="tel", it'll work like type="number" in mobile, and accept maxlength:

<input type="tel" />

Second: Use a little bit of JavaScript:

<!-- maxlength="2" -->
<input type="tel" onKeyDown="if(this.value.length==2 && event.keyCode!=8) return false;" />

What does T&& (double ampersand) mean in C++11?

The term for T&& when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.

That is because it may be either r-value or l-value.

Examples are:

// template
template<class T> foo(T&& t) { ... }

// auto
auto&& t = ...;

// typedef
typedef ... T;
T&& t = ...;

// decltype
decltype(...)&& t = ...;

More discussion can be found in the answer for: Syntax for universal references

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How can I check if a value is a json object?

If you have jQuery, use isPlainObject.

if ($.isPlainObject(my_var)) {}

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

Copy data from one column to other column (which is in a different table)

A similar question's answer worked more correctly for me than this question's selected answer (by Mark Byers). Using Mark's answer, my updated column got the same value in all the rows (perhaps the value from the first row that matched the join). Using ParveenaArora's answer from the other thread updated the column with the correct values.

Transforming Parveena's solution to use this question' table and column names, the query would be as follows (where I assume the tables are related through tblindiantime.contact_id):

UPDATE tblindiantime
SET CountryName = contacts.BusinessCountry
FROM contacts
WHERE tblindiantime.contact_id = contacts.id;

Difference between jQuery .hide() and .css("display", "none")

no difference

With no parameters, the .hide() method is the simplest way to hide an element:

$('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

Same about show

what is reverse() in Django

There is a doc for that

https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls

it can be used to generate an URL for a given view

main advantage is that you do not hard code routes in your code.

How to write to the Output window in Visual Studio?

Use OutputDebugString instead of afxDump.

Example:

#define _TRACE_MAXLEN 500

#if _MSC_VER >= 1900
#define _PRINT_DEBUG_STRING(text) OutputDebugString(text)
#else // _MSC_VER >= 1900
#define _PRINT_DEBUG_STRING(text) afxDump << text
#endif // _MSC_VER >= 1900

void MyTrace(LPCTSTR sFormat, ...)
{
    TCHAR text[_TRACE_MAXLEN + 1];
    memset(text, 0, _TRACE_MAXLEN + 1);
    va_list args;
    va_start(args, sFormat);
    int n = _vsntprintf(text, _TRACE_MAXLEN, sFormat, args);
    va_end(args);
    _PRINT_DEBUG_STRING(text);
    if(n <= 0)
        _PRINT_DEBUG_STRING(_T("[...]"));
}

Generating unique random numbers (integers) between 0 and 'x'

Here's a simple, one-line solution:

var limit = 10;
var amount = 3;

randoSequence(1, limit).slice(0, amount);

It uses randojs.com to generate a randomly shuffled array of integers from 1 through 10 and then cuts off everything after the third integer. If you want to use this answer, toss this within the head tag of your HTML document:

<script src="https://randojs.com/1.0.0.js"></script>

Is it possible to import a whole directory in sass using @import?

If you are using Sass in a Rails project, the sass-rails gem, https://github.com/rails/sass-rails, features glob importing.

@import "foo/*"     // import all the files in the foo folder
@import "bar/**/*"  // import all the files in the bar tree

To answer the concern in another answer "If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity."

Some would argue that organizing your files into directories can REDUCE complexity.

My organization's project is a rather complex app. There are 119 Sass files in 17 directories. These correspond roughly to our views and are mainly used for adjustments, with the heavy lifting being handled by our custom framework. To me, a few lines of imported directories is a tad less complex than 119 lines of imported filenames.

To address load order, we place files that need to load first – mixins, variables, etc. — in an early-loading directory. Otherwise, load order is and should be irrelevant... if we are doing things properly.

How do I filter query objects by date range in Django?

Is simple,

YourModel.objects.filter(YOUR_DATE_FIELD__date=timezone.now())

Works for me

ThreeJS: Remove object from scene

I started to save this as a function, and call it as needed for whatever reactions require it:

function Remove(){
    while(scene.children.length > 0){ 
    scene.remove(scene.children[0]); 
}
}

Now you can call the Remove(); function where appropriate.

Detect click outside React component

Here is the solution that best worked for me without attaching events to the container:

Certain HTML elements can have what is known as "focus", for example input elements. Those elements will also respond to the blur event, when they lose that focus.

To give any element the capacity to have focus, just make sure its tabindex attribute is set to anything other than -1. In regular HTML that would be by setting the tabindex attribute, but in React you have to use tabIndex (note the capital I).

You can also do it via JavaScript with element.setAttribute('tabindex',0)

This is what I was using it for, to make a custom DropDown menu.

var DropDownMenu = React.createClass({
    getInitialState: function(){
        return {
            expanded: false
        }
    },
    expand: function(){
        this.setState({expanded: true});
    },
    collapse: function(){
        this.setState({expanded: false});
    },
    render: function(){
        if(this.state.expanded){
            var dropdown = ...; //the dropdown content
        } else {
            var dropdown = undefined;
        }

        return (
            <div className="dropDownMenu" tabIndex="0" onBlur={ this.collapse } >
                <div className="currentValue" onClick={this.expand}>
                    {this.props.displayValue}
                </div>
                {dropdown}
            </div>
        );
    }
});

Trying to retrieve first 5 characters from string in bash error?

echo $TESTSTRINGONE|awk '{print substr($0,0,5)}'

What is the difference between == and equals() in Java?

== can be used in many object types but you can use Object.equals for any type , especially Strings and Google Map Markers.

C# windows application Event: CLR20r3 on application start

To solve CLR20r3 problem set - Local User Policy \ Computer Configuration \ Windows Settings \ Security Settings \ Local Policies \ Security Options - System cryptography: Use FIPS 140 compliant cryptographic algorithms, including encryption, hashing and signing - Disable

how to POST/Submit an Input Checkbox that is disabled?

Unfortunately there is no 'simple' solution. The attribute readonly cannot be applied to checkboxes. I read the W3 spec about the checkbox and found the culprit:

If a control doesn't have a current value when the form is submitted, user agents are not required to treat it as a successful control. (http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2)

This causes the unchecked state and the disabled state to result in the same parsed value.

  • readonly="readonly" is not a valid attribute for checkboxes.
  • onclick="event.preventDefault();" is not always a good solution as it's triggered on the checkbox itself. But it can work charms in some occasions.
  • Enabling the checkbox onSubmit is not a solution because the control is still not treated as a successful control so the value will not be parsed.
  • Adding another hidden input with the same name in your HTML does not work because the first control value is overwritten by the second control value as it has the same name.

The only full-proof way to do this is to add a hidden input with the same name with javascript on submitting the form.

You can use the small snippet I made for this:

function disabled_checkbox() {
  var theform = document.forms[0];
  var theinputs = theform.getElementsByTagName('input');
  var nrofinputs = theinputs.length;
  for(var inputnr=0;inputnr<nrofinputs;inputnr++) {
    if(theinputs[inputnr].disabled==true) {
      var thevalueis = theinputs[inputnr].checked==true?"on":"";
      var thehiddeninput = document.createElement("input");
      thehiddeninput.setAttribute("type","hidden");
      thehiddeninput.setAttribute("name",theinputs[inputnr].name);
      thehiddeninput.setAttribute("value",thevalueis);
      theinputs[inputnr].parentNode.appendChild(thehiddeninput);
    }
  }
}

This looks for the first form in the document, gathers all inputs and searches for disabled inputs. When a disabled input is found, a hidden input is created in the parentNode with the same name and the value 'on' (if it's state is 'checked') and '' (if it's state is '' - not checked).

This function should be triggered by the event 'onsubmit' in the FORM element as:

<form id='ID' action='ACTION' onsubmit='disabled_checkbox();'>

What Vim command(s) can be used to quote/unquote words?

I wrote a script that does this:

function! WrapSelect (front)
    "puts characters around the selected text.
    let l:front = a:front
    if (a:front == '[')
        let l:back = ']'
    elseif (a:front == '(')
        let l:back = ')'
    elseif (a:front == '{')
        let l:back = '}'
    elseif (a:front == '<')
        let l:back = '>'
    elseif (a:front =~ " ")
        let l:split = split(a:front)
        let l:back = l:split[1]
        let l:front = l:split[0]
    else
        let l:back = a:front
    endif
    "execute: concat all these strings. '.' means "concat without spaces"
    "norm means "run in normal mode and also be able to use \<C-x> characters"
    "gv means "get the previous visual selection back up"
    "c means "cut visual selection and go to insert mode"
    "\<C-R> means "insert the contents of a register. in this case, the
    "default register"
    execute 'norm! gvc' . l:front. "\<C-R>\""  . l:back
endfunction
vnoremap <C-l> :<C-u>call WrapSelect(input('Wrapping? Give both (space separated) or just the first one: '))<cr>

To use, just highlight something, hit control l, and then type a character. If it's one of the characters the function knows about, it'll provide the correct terminating character. If it's not, it'll use the same character to insert on both sides.

Surround.vim can do more than just this, but this was sufficient for my needs.

How to create a sticky navigation bar that becomes fixed to the top after scrolling

I was searching for this very same thing. I had read that this was available in Bootstrap 3.0, but I was having no luck in actually implementing it. This is what I came up with and it works great. Very simple jQuery and Javascript.

Here is the JSFiddle to play around with... http://jsfiddle.net/CriddleCraddle/Wj9dD/

The solution is very similar to other solutions on the web and StackOverflow. If you do not find this one useful, search for what you need. Goodluck!

Here is the HTML...

<div id="banner">
  <h2>put what you want here</h2>
  <p>just adjust javascript size to match this window</p>
</div>

  <nav id='nav_bar'>
    <ul class='nav_links'>
      <li><a href="url">Sign In</a></li>
      <li><a href="url">Blog</a></li>
      <li><a href="url">About</a></li>
    </ul>
  </nav>

<div id='body_div'>
  <p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here</p>
</div>

Here is the CSS...

html, body {
  height: 4000px;
}

.navbar-fixed {
  top: 0;
  z-index: 100;
  position: fixed;
  width: 100%;
}

#body_div {
  top: 0;
  position: relative;
  height: 200px;
  background-color: green;
}

#banner {
  width: 100%;
  height: 273px;
  background-color: gray;
  overflow: hidden;
}

#nav_bar {
  border: 0;
  background-color: #202020;
  border-radius: 0px;
  margin-bottom: 0;
  height: 30px;
}

//the below css are for the links, not needed for sticky nav
.nav_links {
  margin: 0;
}

.nav_links li {
  display: inline-block;
  margin-top: 4px;
}

.nav_links li a {
  padding: 0 15.5px;
  color: #3498db;
  text-decoration: none;
}

Now, just add the javacript to add and remove the fix class based on the scroll position.

$(document).ready(function() {
  //change the integers below to match the height of your upper div, which I called
  //banner.  Just add a 1 to the last number.  console.log($(window).scrollTop())
  //to figure out what the scroll position is when exactly you want to fix the nav
  //bar or div or whatever.  I stuck in the console.log for you.  Just remove when
  //you know the position.
  $(window).scroll(function () { 

    console.log($(window).scrollTop());

    if ($(window).scrollTop() > 550) {
      $('#nav_bar').addClass('navbar-fixed-top');
    }

    if ($(window).scrollTop() < 551) {
      $('#nav_bar').removeClass('navbar-fixed-top');
    }
  });
});

Mongoose and multiple database in single node.js project

As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.

var Mongoose = require('mongoose').Mongoose;

var instance1 = new Mongoose();
instance1.connect('foo');

var instance2 = new Mongoose();
instance2.connect('bar');

This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.

Accessing dict_keys element by index in Python3

test = {'foo': 'bar', 'hello': 'world'}
ls = []
for key in test.keys():
    ls.append(key)
print(ls[0])

Conventional way of appending the keys to a statically defined list and then indexing it for same

How to see JavaDoc in IntelliJ IDEA?

Use View | Quick Documentation or the corresponding keyboard shortcut (by default: Ctrl+Q on Windows/Linux and Ctrl+J on macOS or F1 in the recent IDE versions). See the documentation for more information.

It's also possible to enable automatic JavaDoc popup on explicit (invoked by a shortcut) code completion in Settings | Editor | General | Code completion (Autopopup documentation):

autopopup documentation

Yet another way to see the quick doc is on mouse move:

on mouse move

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.

The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.

Here is a good article about fluid vs. flex.

How to delete a selected DataGridViewRow and update a connected database table?

   ArrayList bkgrefs = new ArrayList();
                    foreach (GridViewRow rowd in grdOptionExtraDetails.Rows)
                    {
                        CheckBox cbf = (CheckBox)rowd.Cells[1].FindControl("chkbulk");

                            if (cbf.Checked)
                            {
                                rowd.Visible = true;
                                 bkgrefs.Add(Convert.ToString(grdOptionExtraDetails.Data.Rows[rowd.RowIndex]["OptionID"]));

                            }
                            else
                            {
                                grdOptionExtraDetails.Data.Rows.RemoveAt(rowd.DataItemIndex);
                                rowd.Visible = false;
                            }


                    }

413 Request Entity Too Large - File Upload Issue

Source: http://www.cyberciti.biz/faq/linux-unix-bsd-nginx-413-request-entity-too-large/

Edit the conf file of nginx:

nano /etc/nginx/nginx.conf

Add a line in the http section:

http {
    client_max_body_size 100M;
}

Doen't use MB it will not work, only the M!

Also do not forget to restart nginx

systemctl restart nginx

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

How can I specify the required Node.js version in package.json?

I think you can use the "engines" field:

{ "engines" : { "node" : ">=0.12" } }

As you're saying your code definitely won't work with any lower versions, you probably want the "engineStrict" flag too:

{ "engineStrict" : true }

Documentation for the package.json file can be found on the npmjs site

Update

engineStrict is now deprecated, so this will only give a warning. It's now down to the user to run npm config set engine-strict true if they want this.

Update 2

As ben pointed out below, creating a .npmrc file at the root of your project (the same level as your package.json file) with the text engine-strict=true will force an error during installation if the Node version is not compatible.

Using margin / padding to space <span> from the rest of the <p>

Use div instead of span, or add display: block; to your css style for the span tag.

sed one-liner to convert all uppercase to lowercase?

With tr:

# Converts upper to lower case 
$ tr '[:upper:]' '[:lower:]' < input.txt > output.txt

# Converts lower to upper case
$ tr '[:lower:]' '[:upper:]' < input.txt > output.txt

Or, sed on GNU (but not BSD or Mac as they don't support \L or \U):

# Converts upper to lower case
$ sed -e 's/\(.*\)/\L\1/' input.txt > output.txt

# Converts lower to upper case
$ sed -e 's/\(.*\)/\U\1/' input.txt > output.txt
 

Batch program to to check if process exists

TASKLIST does not set errorlevel.

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch

Jquery Date picker Default Date

Are u using this datepicker http://jqueryui.com/demos/datepicker/ ? if yes there are options to set the default Date.If you didn't change anything , by default it will show the current date.

any way this will gives current date

$( ".selector" ).datepicker({ defaultDate: new Date() });

Synchronizing a local Git repository with a remote one

You want to do

git fetch --prune origin
git reset --hard origin/master
git clean -f -d

This makes your local repo exactly like your remote repo.

Remember to replace origin and master with the remote and branch that you want to synchronize with.

Average of multiple columns

You could simply do:

Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID

Right?

I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID

How to generate a HTML page dynamically using PHP?

I suggest you to use URL rewrite mod is enough for your problem,I have the same problem but using URL rewrite mod and getting good SEO response. I can give you a small example. Example is that you consider WordPress , here the data is stored in database but using URL rewrite mod many WordPress websites getting good responses from Google and got rank also.

Example: wordpress url with out url rewrite mod -- domain.com/?p=123 after url rewrite mode -- domain.com/{title of article} like domain.com/seo-url-rewrite-mod

i think you have understood what i want to say you

Styling the last td in a table with css

This is the code that will add border for all the nodes and will remove the border for the last node(TD).

<style type="text/css">
    body {  
        font-family:arial;font-size: 8pt;  
    }  
    table td{
        border-right: #666 1px solid
    }  

    table td {  
        h: expression(this.style.border = (this == this.parentNode.lastChild ? 'none' : 'border-right:  0px solid' ) );  
    }  
</style>
<table>
    <tr>
        <td>Home</td>
        <td>sunil</td>
        <td>Kumar</td>
        <td>Rayadurg</td>
        <td>Five</td>
        <td>Six</td>
    </tr>
</table>

Enjoy ...

I want the same instead of border I wanted it using images ... :-)

What does [STAThread] do?

The STAThreadAttribute is essentially a requirement for the Windows message pump to communicate with COM components. Although core Windows Forms does not use COM, many components of the OS such as system dialogs do use this technology.

MSDN explains the reason in slightly more detail:

STAThreadAttribute indicates that the COM threading model for the application is single-threaded apartment. This attribute must be present on the entry point of any application that uses Windows Forms; if it is omitted, the Windows components might not work correctly. If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms.

This blog post (Why is STAThread required?) also explains the requirement quite well. If you want a more in-depth view as to how the threading model works at the CLR level, see this MSDN Magazine article from June 2004 (Archived, Apr. 2009).

Best way to display data via JSON using jQuery

Perfect! Thank you Jay, below is my HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
    $.getJSON("readJSON.php",function(data){
        $.each(data.post, function(i,post){
            content += '<p>' + post.post_author + '</p>';
            content += '<p>' + post.post_content + '</p>';
            content += '<p' + post.date + '</p>';
            content += '<br/>';
            $(content).appendTo("#posts");
        });
    });   
});
/* ]]> */
</script>
</head>
<body>
        <div class="container">
                <div class="span-24">
                       <h2>Check out the following posts:</h2>
                        <div id="posts">
                        </di>
                </div>
        </div>
</body>
</html>

And my JSON outputs:

{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}

I get this error, when I run my code:

object is undefined
http://localhost:8888/rks/post/js/jquery.js
Line 19

How to implement infinity in Java?

I'm not sure that Java has infinity for every numerical type but for some numerical data types the answer is positive:

Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY

or

Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY

Also you may find useful the following article which represents some mathematical operations involving +/- infinity: Java Floating-Point Number Intricacies.

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar):

17.6.3.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also:

17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

How do I programmatically get the GUID of an application in .NET 2.0

Try the following code. The value you are looking for is stored on a GuidAttribute instance attached to the Assembly

using System.Runtime.InteropServices;

static void Main(string[] args)
{
    var assembly = typeof(Program).Assembly;
    var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute),true)[0];
    var id = attribute.Value;
    Console.WriteLine(id);
}

Can I have multiple background images using CSS?

Yes, it is possible, and has been implemented by popular usability testing website Silverback. If you look through the source code you can see that the background is made up of several images, placed on top of each other.

Here is the article demonstrating how to do the effect can be found on Vitamin. A similar concept for wrapping these 'onion skin' layers can be found on A List Apart.

JavaScript moving element in the DOM

jQuery.fn.swap = function(b){ 
    b = jQuery(b)[0]; 
    var a = this[0]; 
    var t = a.parentNode.insertBefore(document.createTextNode(''), a); 
    b.parentNode.insertBefore(a, b); 
    t.parentNode.insertBefore(b, t); 
    t.parentNode.removeChild(t); 
    return this; 
};

and use it like this:

$('#div1').swap('#div2');

if you don't want to use jQuery you could easily adapt the function.

How to start MySQL with --skip-grant-tables?

If you use mysql 5.6 server and have problems with C:\Program Files\MySQL\MySQL Server 5.6\my.ini:

You should go to C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

You should add skip-grant-tables and then you do not need a password.

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
# server_type=3
[mysqld]
skip-grant-tables

Note: after you are done with your work on skip-grant-tables, you should restore your file of C:\ProgramData\MySQL\MySQL Server 5.6\my.ini.

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

How to retry image pull in a kubernetes Pods?

Try with deleting pod it will try to pull image again.

kubectl delete pod <pod_name> -n <namespace_name>

How to merge two json string in Python?

Merging json objects is fairly straight forward but has a few edge cases when dealing with key collisions. The biggest issues have to do with one object having a value of a simple type and the other having a complex type (Array or Object). You have to decide how you want to implement that. Our choice when we implemented this for json passed to chef-solo was to merge Objects and use the first source Object's value in all other cases.

This was our solution:

from collections import Mapping
import json


original = json.loads(jsonStringA)
addition = json.loads(jsonStringB)

for key, value in addition.iteritems():
    if key in original:
        original_value = original[key]
        if isinstance(value, Mapping) and isinstance(original_value, Mapping):
            merge_dicts(original_value, value)
        elif not (isinstance(value, Mapping) or 
                  isinstance(original_value, Mapping)):
            original[key] = value
        else:
            raise ValueError('Attempting to merge {} with value {}'.format(
                key, original_value))
    else:
        original[key] = value

You could add another case after the first case to check for lists if you want to merge those as well, or for specific cases when special keys are encountered.

How to determine a Python variable's type?

Use the type() builtin function:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

To check if a variable is of a given type, use isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

Note that Python doesn't have the same types as C/C++, which appears to be your question.

Reload activity in Android

After login I had the same problem so I used

@Override
protected void onRestart() {
    this.recreate();
    super.onRestart();
}

In Java, how do you determine if a thread is running?

To be precise,

Thread.isAlive() returns true if the thread has been started (may not yet be running) but has not yet completed its run method.

Thread.getState() returns the exact state of the thread.

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

In my case, I'm receiving several parameters as @HeaderParam into a web service method.

These parameters MUST be declared in your CORS filter that way:

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        ...
        headers.add("Access-Control-Allow-Headers", 
        /*
         * name of the @HeaderParam("name") must be declared here (raw String):
         */
        "name", ...);
        headers.add("Access-Control-Allow-Credentials", "true");
        headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");   
    }
}

Angular2 dynamic change CSS property

1) Using inline styles

<div [style.color]="myDynamicColor">

2) Use multiple CSS classes mapping to what you want and switch classes like:

 /* CSS */
 .theme { /* any shared styles */ }
 .theme.blue { color: blue; }
 .theme.red { color: red; }

 /* Template */
 <div class="theme" [ngClass]="{blue: isBlue, red: isRed}">
 <div class="theme" [class.blue]="isBlue">

Code samples from: https://angular.io/cheatsheet

More info on ngClass directive : https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

'NOT NULL constraint failed' after adding to models.py

Since you added a new property to the model, you must first delete the database. Then manage.py migrations then manage.py migrate.

node.js: cannot find module 'request'

You should simply install request locally within your project.

Just cd to the folder containing your js file and run

npm install request

Bootstrap 4 align navbar items to the right

In my case, I wanted just one set of navigation buttons / options and found that this will work:

<div class="collapse navbar-collapse justify-content-end" id="navbarCollapse">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#">Sign Out</a>
    </li>
  </ul>
</div>

So, you will add justify-content-end to the div and omit mr-auto on the list.

Here is a working example.

Getting unique items from a list

You can use Distinct extension method from LINQ

javascript object max size limit

There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.

The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.

To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.

Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:

var items = $.map(keys, function(item, i) {
  var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
  return
    '{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
    '" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
  '{"code":"' + code + '",'+
  '"defaultfile":"' + defaultfile + '",'+
  '"filename":"' + currentFile + '",'+
  '"lstResDef":[' + items.join(',') + ']}';

How do I store and retrieve a blob from sqlite?

In C++ (without error checking):

std::string blob = ...; // assume blob is in the string


std::string query = "INSERT INTO foo (blob_column) VALUES (?);";

sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(), 
                  SQLITE_TRANSIENT);

That can be SQLITE_STATIC if the query will be executed before blob gets destructed.

Android Layout Weight

It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.

How do I clone a subdirectory only of a Git repository?

Using Linux? And only want easy to access and clean working tree ? without bothering rest of code on your machine. try symlinks!

git clone https://github.com:{user}/{repo}.git ~/my-project
ln -s ~/my-project/my-subfolder ~/Desktop/my-subfolder

Test

cd ~/Desktop/my-subfolder
git status

Cloud Firestore collection count

There is no direct option available. You cant't do db.collection("CollectionName").count(). Below are the two ways by which you can find the count of number of documents within a collection.

1 :- Get all the documents in the collection and then get it's size.(Not the best Solution)

db.collection("CollectionName").get().subscribe(doc=>{
console.log(doc.size)
})

By using above code your document reads will be equal to the size of documents within a collection and that is the reason why one must avoid using above solution.

2:- Create a separate document with in your collection which will store the count of number of documents in the collection.(Best Solution)

db.collection("CollectionName").doc("counts")get().subscribe(doc=>{
console.log(doc.count)
})

Above we created a document with name counts to store all the count information.You can update the count document in the following way:-

  • Create a firestore triggers on the document counts
  • Increment the count property of counts document when a new document is created.
  • Decrement the count property of counts document when a document is deleted.

w.r.t price (Document Read = 1) and fast data retrieval the above solution is good.

Video 100% width and height

use this css for height

height: calc(100vh) !important;

This will make the video to have 100% vertical height available.

How to check if spark dataframe is empty?

I found that on some cases:

>>>print(type(df))
<class 'pyspark.sql.dataframe.DataFrame'>

>>>df.take(1).isEmpty
'list' object has no attribute 'isEmpty'

this is same for "length" or replace take() by head()

[Solution] for the issue we can use.

>>>df.limit(2).count() > 1
False

How to cast int to enum in C++?

Your code

enum Test
{
    A, B
}

int a = 1;

Solution

Test castEnum = static_cast<Test>(a);

Best way to update an element in a generic List

If the list is sorted (as happens to be in the example) a binary search on index certainly works.

    public static Dog Find(List<Dog> AllDogs, string Id)
    {
        int p = 0;
        int n = AllDogs.Count;
        while (true)
        {
            int m = (n + p) / 2;
            Dog d = AllDogs[m];
            int r = string.Compare(Id, d.Id);
            if (r == 0)
                return d;
            if (m == p)
                return null;
            if (r < 0)
                n = m;
            if (r > 0)
                p = m;
        }
    }

Not sure what the LINQ version of this would be.

What data type to use for money in Java?

An integral type representing the smallest value possible. In other words your program should think in cents not in dollars/euros.

This should not stop you from having the gui translate it back to dollars/euros.

How to properly exit a C# application?

Do you do:

Application.Run(myForm);

in your Main()?

I found it a very easy way to kill the application when the form is closed.

WooCommerce: Finding the products in database

The following tables are store WooCommerce products database :

  • wp_posts -

    The core of the WordPress data is the posts. It is stored a post_type like product or variable_product.

  • wp_postmeta-

    Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id of product in wp_postmeta table.

Product categories, subcategories stored in this table :

  • wp_terms
  • wp_termmeta
  • wp_term_taxonomy
  • wp_term_relationships
  • wp_woocommerce_termmeta

following Query Return a list of product categories

SELECT wp_terms.* 
    FROM wp_terms 
    LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
    WHERE wp_term_taxonomy.taxonomy = 'product_cat';

for more reference -

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

An other way of CASE:

SELECT *  
FROM MyTable
WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL     THEN 1 
               WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1 
               WHEN @myParm = value3                          THEN 1 
          END

Handling NULL values in Hive

I use below sql to exclude the null string and empty string lines.

select * from table where length(nvl(column1,0))>0

Because, the length of empty string is 0.

select length('');
+-----------+--+
| length()  |
+-----------+--+
| 0         |
+-----------+--+

Key value pairs using JSON

A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.

The JSON for that would look like this:

{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}

Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:

var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);

If you have the key as a string, you can use index notation:

var key = 'KEY3';
var obj = data[key];

select the TOP N rows from a table

From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:

https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15#using-offset-and-fetch-to-limit-the-rows-returned

Your query become:

SELECT * FROM Reflow  
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
OFFSET 20 ROWS  
FETCH NEXT 20 ROWS ONLY;  

Php - testing if a radio button is selected and get the value

A very more efficient way to do this in php:

<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];  // Storing Selected Value In Variable
echo "You have selected :" .$selected_val;  // Displaying Selected Value
}
?>

and for check boxes multiple choice:

<form action="#" method="post">
<select name="Color[]" multiple> // Initializing Name With An Array
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
// As output of $_POST['Color'] is an array we have to use foreach Loop to display individual value
foreach ($_POST['Color'] as $select)
{
echo "You have selected :" .$select; // Displaying Selected Value
}
?> 

How to scroll UITableView to specific position

It is worth noting that if you use the setContentOffset approach, it may cause your table view/collection view to jump a little. I would honestly try to go about this another way. A recommendation is to use the scroll view delegate methods you are given for free.

No server in windows>preferences

In Eclipse Kepler,

  1. go to Help, select ‘Install New Software’
  2. Choose “Kepler- http://download.eclipse.org/releases/kepler” site or add it in if it’s missing.
  3. Expand “Web, XML, and Java EE Development” section Check JST Server Adapters and JST Server Adapters Extensions and install it

After Eclipse restart, go to Window / Preferences / Server / Runtime Environments

adb uninstall failed

Mine was on samsung j7 pro, issue was simple.

j7y17lte:/system $ pm list packages|grep airtel                                                                                                                                                                                            
package:com.samsung.android.airtel.stubapp

j7y17lte:/system $ pm uninstall -k --user 0 com.samsung.android.airtel.stubapp

DO NO-NOT include the word package in the unistall command

How do I concatenate strings and variables in PowerShell?

There is a difference between single and double quotes. (I am using PowerShell 4).

You can do this (as Benjamin said):

$name = 'Slim Shady'
Write-Host 'My name is'$name
-> My name is Slim Shady

Or you can do this:

$name = 'Slim Shady'
Write-Host "My name is $name"
-> My name is Slim Shady

The single quotes are for literal, output the string exactly like this, please. The double quotes are for when you want some pre-processing done (such as variables, special characters, etc.)

So:

$name = "Marshall Bruce Mathers III"
Write-Host "$name"
-> Marshall Bruce Mathers III

Whereas:

$name = "Marshall Bruce Mathers III"
Write-Host '$name'
-> $name

(I find How-to: Escape characters, Delimiters and Quotes good for reference).

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

calculate the mean for each column of a matrix in R

You can try this:

mean(as.matrix(cluster1))

Find and replace with a newline in Visual Studio Code

A possible workaround would be to use the multi-cursor. select the >< part of your example use Ctrl+Shift+L or select all occurrences. Then use the arrow keys to move all the cursors between the tags and press enter to insert a newline everywhere.

This won't work in all situations.

You can also use Ctrl+D for select next match, which adds the next match to the selection and adds a cursor. And use Ctrl+K Ctrl+D to skip a selection.

Which MySQL data type to use for storing boolean values

For MySQL 5.0.3 and higher, you can use BIT. The manual says:

As of MySQL 5.0.3, the BIT data type is used to store bit-field values. A type of BIT(M) enables storage of M-bit values. M can range from 1 to 64.

Otherwise, according to the MySQL manual you can use BOOL or BOOLEAN, which are at the moment aliases of tinyint(1):

Bool, Boolean: These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.

MySQL also states that:

We intend to implement full boolean type handling, in accordance with standard SQL, in a future MySQL release.

References: http://dev.mysql.com/doc/refman/5.5/en/numeric-type-overview.html

Make a table fill the entire window

Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>

refresh both the External data source and pivot tables together within a time schedule

I think there is a simpler way to make excel wait till the refresh is done, without having to set the Background Query property to False. Why mess with people's preferences right?

Excel 2010 (and later) has this method called CalculateUntilAsyncQueriesDone and all you have to do it call it after you have called the RefreshAll method. Excel will wait till the calculation is complete.

ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone

I usually put these things together to do a master full calculate without interruption, before sending my models to others. Something like this:

ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone
Application.CalculateFullRebuild
Application.CalculateUntilAsyncQueriesDone

MySQL/Writing file error (Errcode 28)

The error means that you dont have enough space to create temp files needed by MySQL.

The first thing you can try is to expand the size of your /tmp/ partition. If you are under LVM, check the lvextend command.

If you are not able to increase the size of your partition /tmp/ you can work in the MySQL configuration, edit the my.cnf (typically on /etc/mysql/my.cnf) file and look for this line:

tmpdir = /tmp/

Change it for whatever you want (example /var/tmp/). Just be sure to have space and assign write permission for the mysql user in the new directory.

Hope this helps!

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

I had the same issue trying to do something the same as you and I fixed it with something similar to Richie Fredicson's answer.

When you run createComponent() it is created with undefined input variables. Then after that when you assign data to those input variables it changes things and causes that error in your child template (in my case it was because I was using the input in an ngIf, which changed once I assigned the input data).

The only way I could find to avoid it in this specific case is to force change detection after you assign the data, however I didn't do it in ngAfterContentChecked().

Your example code is a bit hard to follow but if my solution works for you it would be something like this (in the parent component):

export class ParentComponent implements AfterViewInit {
  // I'm assuming you have a WidgetDirective.
  @ViewChild(WidgetDirective) widgetHost: WidgetDirective;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private changeDetector: ChangeDetectorRef
  ) {}

  ngAfterViewInit() {
    renderWidgetInsideWidgetContainer();
  }

  renderWidgetInsideWidgetContainer() {
    let component = this.storeFactory.getWidgetComponent(this.dataSource.ComponentName);
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
    let viewContainerRef = this.widgetHost.viewContainerRef;
    viewContainerRef.clear();
    let componentRef = viewContainerRef.createComponent(componentFactory);
    debugger;
    // This <IDataBind> type you are using here needs to be changed to be the component
    // type you used for the call to resolveComponentFactory() above (if it isn't already).
    // It tells it that this component instance if of that type and then it knows
    // that WidgetDataContext and WidgetPosition are @Inputs for it.
    (<IDataBind>componentRef.instance).WidgetDataContext = this.dataSource.DataContext;
    (<IDataBind>componentRef.instance).WidgetPosition = this.dataSource.Position;
    this.changeDetector.detectChanges();
  }
}

Mine is almost the same as that except I'm using @ViewChildren instead of @ViewChild as I have multiple host elements.

Most common C# bitwise operations on enums

To test a bit you would do the following: (assuming flags is a 32 bit number)

Test Bit:

if((flags & 0x08) == 0x08)
(If bit 4 is set then its true) Toggle Back (1 - 0 or 0 - 1):
flags = flags ^ 0x08;
Reset Bit 4 to Zero:
flags = flags & 0xFFFFFF7F;

Telegram Bot - how to get a group chat id?

IMHO the best way to do this is using TeleThon, but given that the answer by apadana is outdated beyond repair, I will write the working solution here:

import os
import sys
from telethon import TelegramClient
from telethon.utils import get_display_name

import nest_asyncio
nest_asyncio.apply()

session_name = "<session_name>"
api_id = <api_id>
api_hash = "<api_hash>"
dialog_count = 10 # you may change this

if f"{session_name}.session" in os.listdir():
    os.remove(f"{session_name}.session")

client = TelegramClient(session_name, api_id, api_hash)

async def main():
    dialogs = await client.get_dialogs(dialog_count)
    for dialog in dialogs:
        print(get_display_name(dialog.entity), dialog.entity.id)

async with client:
    client.loop.run_until_complete(main())

this snippet will give you the first 10 chats in your Telegram.

Assumptions:

  • you have telethon and nest_asyncio installed
  • you have api_id and api_hash from my.telegram.org

Window.open as modal popup?

A pop-up is a child of the parent window, but it is not a child of the parent DOCUMENT. It is its own independent browser window and is not contained by the parent.

Use an absolutely-positioned DIV and a translucent overlay instead.

EDIT - example

You need jQuery for this:

<style>
html, body {
    height:100%
}


#overlay { 
    position:absolute;
    z-index:10;
    width:100%;
    height:100%;
    top:0;
    left:0;
    background-color:#f00;
    filter:alpha(opacity=10);
    -moz-opacity:0.1;
    opacity:0.1;
    cursor:pointer;

} 

.dialog {
    position:absolute;
    border:2px solid #3366CC;
    width:250px;
    height:120px;
    background-color:#ffffff;
    z-index:12;
}

</style>
<script type="text/javascript">
$(document).ready(function() { init() })

function init() {
    $('#overlay').click(function() { closeDialog(); })
}

function openDialog(element) {
    //this is the general dialog handler.
    //pass the element name and this will copy
    //the contents of the element to the dialog box

    $('#overlay').css('height', $(document.body).height() + 'px')
    $('#overlay').show()
    $('#dialog').html($(element).html())
    centerMe('#dialog')
    $('#dialog').show();
}

function closeDialog() {
    $('#overlay').hide();
    $('#dialog').hide().html('');
}

function centerMe(element) {
    //pass element name to be centered on screen
    var pWidth = $(window).width();
    var pTop = $(window).scrollTop()
    var eWidth = $(element).width()
    var height = $(element).height()
    $(element).css('top', '130px')
    //$(element).css('top',pTop+100+'px')
    $(element).css('left', parseInt((pWidth / 2) - (eWidth / 2)) + 'px')
}


</script>


<a href="javascript:;//close me" onclick="openDialog($('#content'))">show dialog A</a>

<a href="javascript:;//close me" onclick="openDialog($('#contentB'))">show dialog B</a>

<div id="dialog" class="dialog" style="display:none"></div>
<div id="overlay" style="display:none"></div>
<div id="content" style="display:none">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisl felis, placerat in sollicitudin quis, hendrerit vitae diam. Nunc ornare iaculis urna. 
</div>

<div id="contentB" style="display:none">
    Moooo mooo moo moo moo!!! 
</div>

Is there a simple way to increment a datetime object one month in Python?

>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)

EDIT: Fails on

y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month

Ther is no simple way to do it, but you can use your own function like answered below.

MySQL Error #1133 - Can't find any matching row in the user table

I encountered this issue, but in my case the password for the 'phpmyadmin' user did not match the contents of /etc/phpmyadmin/config-db.php

Once I updated the password for the 'phpmyadmin' user the error went away.

These are the steps I took:

  1. Log in to mysql as root: mysql -uroot -pYOUR_ROOT_PASS
  2. Change to the 'mysql' db: use mysql;
  3. Update the password for the 'phpmyadmin' user: UPDATE mysql.user SET Password=PASSWORD('YOUR_PASS_HERE') WHERE User='phpmyadmin' AND Host='localhost';
  4. Flush privileges: FLUSH PRIVILEGES;

DONE!! It worked for me.

What is the difference between Bower and npm?

2017-Oct update

Bower has finally been deprecated. End of story.

Older answer

From Mattias Petter Johansson, JavaScript developer at Spotify:

In almost all cases, it's more appropriate to use Browserify and npm over Bower. It is simply a better packaging solution for front-end apps than Bower is. At Spotify, we use npm to package entire web modules (html, css, js) and it works very well.

Bower brands itself as the package manager for the web. It would be awesome if this was true - a package manager that made my life better as a front-end developer would be awesome. The problem is that Bower offers no specialized tooling for the purpose. It offers NO tooling that I know of that npm doesn't, and especially none that is specifically useful for front-end developers. There is simply no benefit for a front-end developer to use Bower over npm.

We should stop using bower and consolidate around npm. Thankfully, that is what is happening:

Module counts - bower vs. npm

With browserify or webpack, it becomes super-easy to concatenate all your modules into big minified files, which is awesome for performance, especially for mobile devices. Not so with Bower, which will require significantly more labor to get the same effect.

npm also offers you the ability to use multiple versions of modules simultaneously. If you have not done much application development, this might initially strike you as a bad thing, but once you've gone through a few bouts of Dependency hell you will realize that having the ability to have multiple versions of one module is a pretty darn great feature. Note that npm includes a very handy dedupe tool that automatically makes sure that you only use two versions of a module if you actually have to - if two modules both can use the same version of one module, they will. But if they can't, you have a very handy out.

(Note that Webpack and rollup are widely regarded to be better than Browserify as of Aug 2016.)

Jquery post, response in new window

Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:

$.post(url, function (data) {
    var w = window.open('about:blank', 'windowname');
    w.document.write(data);
    w.document.close();
});

Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)

How do I capture SIGINT in Python?

Personally, I couldn't use try/except KeyboardInterrupt because I was using standard socket (IPC) mode which is blocking. So the SIGINT was cueued, but came only after receiving data on the socket.

Setting a signal handler behaves the same.

On the other hand, this only works for an actual terminal. Other starting environments might not accept Ctrl+C, or pre-handle the signal.

Also, there are "Exceptions" and "BaseExceptions" in Python, which differ in the sense that interpreter needs to exit cleanly itself, so some exceptions have a higher priority than others (Exceptions is derived from BaseException)

Downloading and unzipping a .zip file without writing to disk

Adding on to the other answers using requests:

 # download from web

 import requests
 url = 'http://mlg.ucd.ie/files/datasets/bbc.zip'
 content = requests.get(url)

 # unzip the content
 from io import BytesIO
 from zipfile import ZipFile
 f = ZipFile(BytesIO(content.content))
 print(f.namelist())

 # outputs ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']

Use help(f) to get more functions details for e.g. extractall() which extracts the contents in zip file which later can be used with with open.

What causes a Python segmentation fault?

Updating the ulimit worked for my Kosaraju's SCC implementation by fixing the segfault on both Python (Python segfault.. who knew!) and C++ implementations.

For my MAC, I found out the possible maximum via :

$ ulimit -s -H
65532

Google Play Services Missing in Emulator (Android 4.4.2)

You will not able to test the app using the Google-Play-Service library in emulator. In order to test that app in emulator you need to install some system framework in your emulator to make it work.

https://stackoverflow.com/a/11213598/1405008

Refer the above answer to install Google play service on your emulator.

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

System.out.println() shortcut on Intellij IDEA

Yeah, you can do it. Just open Settings -> Live Templates. Create new one with syso as abbreviation and System.out.println($END$); as Template text.

is of a type that is invalid for use as a key column in an index

There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table. The condition is:

([dbo].[CheckKey]([key])=(1))

and [dbo].[CheckKey] is a scalar function defined as:

CREATE FUNCTION [dbo].[CheckKey]
(
    @key nvarchar(max)
)
RETURNS bit
AS
BEGIN
    declare @res bit
    if exists(select * from key_value where [key] = @key)
        set @res = 0
    else
        set @res = 1

    return @res
END

But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

How To Make Circle Custom Progress Bar in Android

I have solved this cool custom progress bar by creating the custom view. I have overriden the onDraw() method to draw the circles, filled arc and text on the canvas.

following is the custom progress bar

import android.annotation.TargetApi;

import android.content.Context;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.graphics.Path;

import android.graphics.Rect;

import android.graphics.RectF;

import android.os.Build;

import android.util.AttributeSet;

import android.view.View;

import com.investorfinder.utils.UiUtils;


public class CustomProgressBar extends View {


private int max = 100;

private int progress;

private Path path = new Path();

int color = 0xff44C8E5;

private Paint paint;

private Paint mPaintProgress;

private RectF mRectF;

private Paint textPaint;

private String text = "0%";

private final Rect textBounds = new Rect();

private int centerY;

private int centerX;

private int swipeAndgle = 0;


public CustomProgressBar(Context context) {
    super(context);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    initUI();
}

public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initUI();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initUI();
}

private void initUI() {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(color);


    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
    mPaintProgress.setColor(color);

    textPaint = new Paint();
    textPaint.setAntiAlias(true);
    textPaint.setStyle(Paint.Style.FILL);
    textPaint.setColor(color);
    textPaint.setStrokeWidth(2);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    int viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;

    path.reset();

    centerX = viewWidth / 2;
    centerY = viewHeight / 2;
    path.addCircle(centerX, centerY, radius, Path.Direction.CW);

    int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
    path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
    smallCirclRadius += UiUtils.dpToPx(getContext(), 4);

    mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);

    textPaint.setTextSize(radius * 0.5f);
}


@Override
protected void onDraw(Canvas canvas) {


    super.onDraw(canvas);

    canvas.drawPath(path, paint);

    canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);

    drawTextCentred(canvas);

}

public void drawTextCentred(Canvas canvas) {

    textPaint.getTextBounds(text, 0, text.length(), textBounds);

    canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}

public void setMax(int max) {
    this.max = max;
}

public void setProgress(int progress) {
    this.progress = progress;

    int percentage = progress * 100 / max;

    swipeAndgle = percentage * 360 / 100;

    text = percentage + "%";

    invalidate();
}

public void setColor(int color) {
    this.color = color;
}
}

In layout XML

<com.your.package.name.CustomProgressBar
            android:id="@+id/progress_bar"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/txt_title"
            android:layout_marginRight="15dp" />

in activity

CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);

    progressBar.setMax(9);

    progressBar.setProgress(5);

Get current value selected in dropdown using jQuery

To get the text of the selected option

$("#your_select :selected").text();

To get the value of the selected option

$("#your_select").val();

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In my case I am using Visual Studio and Nuget packages its failing because have duplicated libraries one in the same folder as jQuery and another in the folder umd. By removing the popper javascript files from the same level as jQuery and refere to the popper.js inside the umd folder fixed my issue and I can see the tooltips correctly.

Read properties file outside JAR file

There's always a problem accessing files on your file directory from a jar file. Providing the classpath in a jar file is very limited. Instead try using a bat file or a sh file to start your program. In that way you can specify your classpath anyway you like, referencing any folder anywhere on the system.

Also check my answer on this question:

making .exe file for java project containing sqlite

How do you setLayoutParams() for an ImageView?

You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This is because it's the parent of the View that needs to know what size to allocate to the View.

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.

Difference between require, include, require_once and include_once?

There are require and include_once as well.

So your question should be...

  1. When should I use require vs. include?
  2. When should I use require_once vs. require

The answer to 1 is described here.

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

The answer to 2 can be found here.

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a poor name for a really useful concept.

The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is Bjarne Stroustrup's explanation of the topic.

A common use for RAII is locking a mutex:

// A class with implements RAII
class lock
{
    mutex &m_;

public:
    lock(mutex &m)
      : m_(m)
    {
        m.acquire();
    }
    ~lock()
    {
        m_.release();
    }
};

// A class which uses 'mutex' and 'lock' objects
class foo
{
    mutex mutex_; // mutex for locking 'foo' object
public:
    void bar()
    {
        lock scopeLock(mutex_); // lock object.

        foobar(); // an operation which may throw an exception

        // scopeLock will be destructed even if an exception
        // occurs, which will release the mutex and allow
        // other functions to lock the object and run.
    }
};

RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to Mike B for pointing this out.)

For those familliar with C# or VB.NET, you may recognize that RAII is similar to .NET deterministic destruction using IDisposable and 'using' statements. Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles.

 

† Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom.

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

How do I grab an INI value within a shell script?

Here is my version, which parses sections and populates a global associative array g_iniProperties with it. Note that this works only with bash v4.2 and higher.

function parseIniFile() { #accepts the name of the file to parse as argument ($1)
    #declare syntax below (-gA) only works with bash 4.2 and higher
    unset g_iniProperties
    declare -gA g_iniProperties
    currentSection=""
    while read -r line
    do
        if [[ $line = [*  ]] ; then
            if [[ $line = [* ]] ; then 
                currentSection=$(echo $line | sed -e 's/\r//g' | tr -d "[]")  
            fi
        else
            if [[ $line = *=*  ]] ; then
                cleanLine=$(echo $line | sed -e 's/\r//g')
                key=$currentSection.$(echo $cleanLine | awk -F: '{ st = index($0,"=");print  substr($0,0,st-1)}')
                value=$(echo $cleanLine | awk -F: '{ st = index($0,"=");print  substr($0,st+1)}')
                g_iniProperties[$key]=$value
            fi
        fi;
    done < $1
}

And here is a sample code using the function above:

parseIniFile "/path/to/myFile.ini"
for key in "${!g_iniProperties[@]}"; do
    echo "Found key/value $key = ${g_iniProperties[$key]}"
done

segmentation fault : 11

This declaration:

double F[1000][1000000];

would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

you need to sign the assembly with a key. Go in the project properties under the tab signing: enter image description here

How do I get ruby to print a full backtrace instead of a truncated one?

One liner for callstack:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace; end

One liner for callstack without all the gems's:

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//); end

One liner for callstack without all the gems's and relative to current directory

begin; Whatever.you.want; rescue => e; puts e.message; puts; puts e.backtrace.grep_v(/\/gems\//).map { |l| l.gsub(`pwd`.strip + '/', '') }; end

Combine two tables for one output

In your expected output, you've got the second last row sum incorrect, it should be 40 according to the data in your tables, but here is the query:

Select  ChargeNum, CategoryId, Sum(Hours)
From    (
    Select  ChargeNum, CategoryId, Hours
    From    KnownHours
    Union
    Select  ChargeNum, 'Unknown' As CategoryId, Hours
    From    UnknownHours
) As a
Group By ChargeNum, CategoryId
Order By ChargeNum, CategoryId

And here is the output:

ChargeNum  CategoryId 
---------- ---------- ----------------------
111111     1          40
111111     2          50
111111     Unknown    70
222222     1          40
222222     Unknown    25.5

How do I delete unpushed git commits?

Do a git rebase -i FAR_ENOUGH_BACK and drop the line for the commit you don't want.

How to insert pandas dataframe via mysqldb into database?

Andy Hayden mentioned the correct function (to_sql). In this answer, I'll give a complete example, which I tested with Python 3.5 but should also work for Python 2.7 (and Python 3.x):

First, let's create the dataframe:

# Create dataframe
import pandas as pd
import numpy as np

np.random.seed(0)
number_of_samples = 10
frame = pd.DataFrame({
    'feature1': np.random.random(number_of_samples),
    'feature2': np.random.random(number_of_samples),
    'class':    np.random.binomial(2, 0.1, size=number_of_samples),
    },columns=['feature1','feature2','class'])

print(frame)

Which gives:

   feature1  feature2  class
0  0.548814  0.791725      1
1  0.715189  0.528895      0
2  0.602763  0.568045      0
3  0.544883  0.925597      0
4  0.423655  0.071036      0
5  0.645894  0.087129      0
6  0.437587  0.020218      0
7  0.891773  0.832620      1
8  0.963663  0.778157      0
9  0.383442  0.870012      0

To import this dataframe into a MySQL table:

# Import dataframe into MySQL
import sqlalchemy
database_username = 'ENTER USERNAME'
database_password = 'ENTER USERNAME PASSWORD'
database_ip       = 'ENTER DATABASE IP'
database_name     = 'ENTER DATABASE NAME'
database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.
                                               format(database_username, database_password, 
                                                      database_ip, database_name))
frame.to_sql(con=database_connection, name='table_name_for_df', if_exists='replace')

One trick is that MySQLdb doesn't work with Python 3.x. So instead we use mysqlconnector, which may be installed as follows:

pip install mysql-connector==2.1.4  # version avoids Protobuf error

Output:

enter image description here

Note that to_sql creates the table as well as the columns if they do not already exist in the database.

Keras input explanation: input_shape, units, batch_size, dim, etc

Units:

The amount of "neurons", or "cells", or whatever the layer has inside it.

It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

  • Hidden layer 1: 4 units (4 neurons)
  • Hidden layer 2: 4 units
  • Last layer: 1 unit

Shapes

Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

The input shape

What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

Each type of layer requires the input with a certain number of dimensions:

  • Dense layers require inputs as (batch_size, input_size)
    • or (batch_size, optional,...,optional, input_size)
  • 2D convolutional layers need inputs as:
    • if using channels_last: (batch_size, imageside1, imageside2, channels)
    • if using channels_first: (batch_size, channels, imageside1, imageside2)
  • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).

Weights

Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.

Dim

And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.


Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

$(window).scrollTop() vs. $(document).scrollTop()

First, you need to understand the difference between window and document. The window object is a top level client side object. There is nothing above the window object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document object is an object of the window object. To change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red" 

To answer your question, There is no difference in the end result between window and document scrollTop. Both will give the same output.

Check working example at http://jsfiddle.net/7VRvj/6/

In general use document mainly to register events and use window to do things like scroll, scrollTop, and resize.

How can you find out which process is listening on a TCP or UDP port on Windows?

Follow these tools: From cmd: C:\> netstat -anob with Administrator privileges.

Process Explorer

Process Dump

Port Monitor

All from sysinternals.com.

If you just want to know process running and threads under each process, I recommend learning about wmic. It is a wonderful command-line tool, which gives you much more than you can know.

Example:

c:\> wmic process list brief /every:5

The above command will show an all process list in brief every 5 seconds. To know more, you can just go with /? command of windows , for example,

c:\> wmic /?
c:\> wmic process /?
c:\> wmic prcess list /?

And so on and so forth. :)

Init method in Spring Controller (annotation version)

public class InitHelloWorld implements BeanPostProcessor {

   public Object postProcessBeforeInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("BeforeInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

   public Object postProcessAfterInitialization(Object bean,
             String beanName) throws BeansException {
       System.out.println("AfterInitialization : " + beanName);
       return bean;  // you can return any other object as well
   }

}

How can I change the color of a Google Maps marker?

To customize markers, you can do it from this online tool: https://materialdesignicons.com/

In your case, you want the map-marker which is available here: https://materialdesignicons.com/icon/map-marker and which you can customize online.

If you simply want to change the default Red color to Blue, you can load this icon: http://maps.google.com/mapfiles/ms/icons/blue-dot.png

It's been mentioned in this thread: https://stackoverflow.com/a/32651327/6381715

Python - 'ascii' codec can't decode byte

You use u"??".encode('utf8') to encode an unicode string. But if you want to represent "??", you should decode it. Just like:

"??".decode("utf8")

You will get what you want. Maybe you should learn more about encode & decode.

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)

shopt -s globstar
for xls in /path/**/*.xls
do
  xls2csv "$xls" "${xls%.xls}.csv"
done

heroku - how to see all the logs

You can use heroku logs -n 1500

But this is not a recommended approach(in other word doesn't show you the real picture)

I would suggest you plug some logging tool. ( sumoLogic, paper trail n all ) as an add-on

They all have a free version( with few limitations, though enough for a small app or dev env, which will provide good insight and tool to analyze logs )

How to combine class and ID in CSS selector?

There's nothing wrong with combining an id and a class on one element, but you shouldn't need to identify it by both for one rule. If you really want to you can do:

#content.sectionA{some rules}

You don't need the div in front of the ID as others have suggested.

In general, CSS rules specific to that element should be set with the ID, and those are going to carry a greater weight than those of just the class. Rules specified by the class would be properties that apply to multiple items that you don't want to change in multiple places anytime you need to adjust.

That boils down to this:

 .sectionA{some general rules here}
 #content{specific rules, and overrides for things in .sectionA}

Make sense?

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Remove all padding and margin table HTML and CSS

Use a display block

style= "display: block";

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

How do you append to a file?

The 'a' parameter signifies append mode. If you don't want to use with open each time, you can easily write a function to do it for you:

def append(txt='\nFunction Successfully Executed', file):
    with open(file, 'a') as f:
        f.write(txt)

If you want to write somewhere else other than the end, you can use 'r+':

import os

with open(file, 'r+') as f:
    f.seek(0, os.SEEK_END)
    f.write("text to add")

Finally, the 'w+' parameter grants even more freedom. Specifically, it allows you to create the file if it doesn't exist, as well as empty the contents of a file that currently exists.


Credit for this function goes to @Primusa

Uint8Array to string in Javascript

Try these functions,

var JsonToArray = function(json)
{
    var str = JSON.stringify(json, null, 0);
    var ret = new Uint8Array(str.length);
    for (var i = 0; i < str.length; i++) {
        ret[i] = str.charCodeAt(i);
    }
    return ret
};

var binArrayToJson = function(binArray)
{
    var str = "";
    for (var i = 0; i < binArray.length; i++) {
        str += String.fromCharCode(parseInt(binArray[i]));
    }
    return JSON.parse(str)
}

source: https://gist.github.com/tomfa/706d10fed78c497731ac, kudos to Tomfa

Java: Insert multiple rows into MySQL with PreparedStatement

If you can create your sql statement dynamically you can do following workaround:

String myArray[][] = { { "1-1", "1-2" }, { "2-1", "2-2" }, { "3-1", "3-2" } };

StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");

for (int i = 0; i < myArray.length - 1; i++) {
    mySql.append(", (?, ?)");
}

myStatement = myConnection.prepareStatement(mySql.toString());

for (int i = 0; i < myArray.length; i++) {
    myStatement.setString(i, myArray[i][1]);
    myStatement.setString(i, myArray[i][2]);
}
myStatement.executeUpdate();

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

Pandas get topmost n records within each group

Did you try df.groupby('id').head(2)

Ouput generated:

>>> df.groupby('id').head(2)
       id  value
id             
1  0   1      1
   1   1      2 
2  3   2      1
   4   2      2
3  7   3      1
4  8   4      1

(Keep in mind that you might need to order/sort before, depending on your data)

EDIT: As mentioned by the questioner, use df.groupby('id').head(2).reset_index(drop=True) to remove the multindex and flatten the results.

>>> df.groupby('id').head(2).reset_index(drop=True)
    id  value
0   1      1
1   1      2
2   2      1
3   2      2
4   3      1
5   4      1

How to extract the substring between two markers?

Surprised that nobody has mentioned this which is my quick version for one-off scripts:

>>> x = 'gfgfdAAA1234ZZZuijjk'
>>> x.split('AAA')[1].split('ZZZ')[0]
'1234'

Multiplication on command line terminal

I use this function which uses bc and thus supports floating point calculations:

c () { 
    local a
    (( $# > 0 )) && a="$@" || read -r -p "calc: " a
    bc -l <<< "$a"
}

Example:

$ c '5*5'
25
$ c 5/5
1.00000000000000000000
$ c 3.4/7.9
.43037974683544303797

Bash's arithmetic expansion doesn't support floats (but Korn shell and zsh do).

Example:

$ ksh -c 'echo "$((3.0 / 4))"'
0.75

Git credential helper - update password

None of the current solutions worked for me with git bash 2.26.2. This should work in any case if you are using the windows credential manager.

One issue is the windows credential manager runs for the logged user. In my case for example, I run git bash with right click, run as admin. Therefore, my stored credentials are in a credentials manager which I can't access with the windows GUI if I don't login to windows as admin.

To fix this:

  • Open a cmd as admin (or whatever user you run with bash with)
  • Go to windows/system32
  • Type cmdkey /list. Your old credentials should appear here, with a part that reads ...target:xxx...
  • Type cmdkey /delete:xxx, where xxx is the target from the previous line

It should confirm you that your credentials have been removed. Next time you do any operation in git bash that requires authentication, a popup will ask for your credentials.

jquery live hover

$('.hoverme').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});

http://api.jquery.com/live/

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Bash if statement with multiple conditions throws an error

Please try following

if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
then
    echo "WORKING"
else
    echo "Out of range!"

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

IF you want to handle 'standard' JSON representation of the Date then better to use this pattern: "yyyy-MM-dd'T'HH:mm:ssX".

Notice the X on the end. It will handle timezones in ISO 8601 standard, and ISO 8601 is exactly what produces this statement in Javascript new Date().toJSON()

Comparing to other answers it has some benefits:

  1. You don't need to require your clients to send date in GMT
  2. You don't need to explicitly convert your Date object to GMT using this: sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

Move the mouse pointer to a specific position?

You can't move a mouse but can lock it. Note: that you must call requestPointerLock in click event.

Small Example:

var canvas = document.getElementById('mycanvas');
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
canvas.requestPointerLock();

Documentation and full code example:

https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API

How to read a single character at a time from a file in Python?

First, open a file:

with open("filename") as fileobj:
    for line in fileobj:  
       for ch in line: 
           print(ch)

This goes through every line in the file and then every character in that line.

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

If you not want include other function like 'ReDimPreserve' could use temporal matrix for resizing. On based to your code:

 Dim n As Integer, m As Integer, i as Long, j as Long
 Dim arrTemporal() as Variant

    n = 1
    m = 0
    Dim arrCity() As String
    ReDim arrCity(n, m)

    n = n + 1
    m = m + 1

    'VBA automatically adapts the size of the receiving matrix.
    arrTemporal = arrCity
    ReDim arrCity(n, m)

    'Loop for assign values to arrCity
    For i = 1 To UBound(arrTemporal , 1)
        For j = 1 To UBound(arrTemporal , 2)
            arrCity(i, j) = arrTemporal (i, j)
        Next
    Next

If you not declare of type VBA assume that is Variant.

Dim n as Integer, m As Integer

Variable used in lambda expression should be final or effectively final

From a lambda, you can't get a reference to anything that isn't final. You need to declare a final wrapper from outside the lamda to hold your variable.

I've added the final 'reference' object as this wrapper.

private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
    final AtomicReference<TimeZone> reference = new AtomicReference<>();

    try {
       cal.getComponents().getComponents("VTIMEZONE").forEach(component->{
        VTimeZone v = (VTimeZone) component;
           v.getTimeZoneId();
           if(reference.get()==null) {
               reference.set(TimeZone.getTimeZone(v.getTimeZoneId().getValue()));
           }
           });
    } catch (Exception e) {
        //log.warn("Unable to determine ical timezone", e);
    }
    return reference.get();
}   

Should you commit .gitignore into the Git repos?

I put commit .gitignore, which is a courtesy to other who may build my project that the following files are derived and should be ignored.

I usually do a hybrid. I like to make makefile generate the .gitignore file since the makefile will know all the files associated with the project -derived or otherwise. Then have a top level project .gitignore that you check in, which would ignore the generated .gitignore files created by the makefile for the various sub directories.

So in my project, I might have a bin sub directory with all the built executables. Then, I'll have my makefile generate a .gitignore for that bin directory. And in the top directory .gitignore that lists bin/.gitignore. The top one is the one I check in.

How to launch an EXE from Web page (asp.net)

Did you try a UNC share?

\\server\share\foo.exe

How to count digits, letters, spaces for a string in Python?

You shouldn't be setting x = []. That is setting an empty list to your inputted parameter. Furthermore, use python's for i in x syntax as follows:

for i in x:
    if i.isalpha():
        letters+=1
    elif i.isnumeric():
        digit+=1
    elif i.isspace():
        space+=1
    else:
        other+=1

Node.js - EJS - including a partial

Express 3.x no longer support partial. According to the post ejs 'partial is not defined', you can use "include" keyword in EJS to replace the removed partial functionality.

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

Send JSON data with jQuery

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

Multi-character constant warnings

Even if you're willing to look up what behavior your implementation defines, multi-character constants will still vary with endianness.

Better to use a (POD) struct { char[4] }; ... and then use a UDL like "WAVE"_4cc to easily construct instances of that class

How do I call one constructor from another in Java?

Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor.

Example:

Class Test {
    Test() {
        this(10); // calls the constructor with integer args, Test(int a)
    }
    Test(int a) {
        this(10.5); // call the constructor with double arg, Test(double a)
    }
    Test(double a) {
        System.out.println("I am a double arg constructor");
    }
}

This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.

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

Just found the answer, it appears that the view where I was placing the RenderPartial code had a dynamic model, and thus, MVC couldn't choose the correct method to use. Casting the model in the RenderPartial call to the correct type fixed the issue.

source: Using Html.RenderPartial() in ascx files

Map implementation with duplicate keys

If you want iterate about a list of key-value-pairs (as you wrote in the comment), then a List or an array should be better. First combine your keys and values:

public class Pair
{
   public Class1 key;
   public Class2 value;

   public Pair(Class1 key, Class2 value)
   {
      this.key = key;
      this.value = value;
   }

}

Replace Class1 and Class2 with the types you want to use for keys and values.

Now you can put them into an array or a list and iterate over them:

Pair[] pairs = new Pair[10];
...
for (Pair pair : pairs)
{
   ...
}

Error in <my code> : object of type 'closure' is not subsettable

You don't define the vector, url, before trying to subset it. url is also a function in the base package, so url[i] is attempting to subset that function... which doesn't make sense.

You probably defined url in your prior R session, but forgot to copy that code to your script.

Convert dictionary values into array

// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

Javascript Equivalent to PHP Explode()

So I know that this post is pretty old, but I figured I may as well add a function that has helped me over the years. Why not just remake the explode function using split as mentioned above? Well here it is:

function explode(str,begin,end)
{
   t=str.split(begin);
   t=t[1].split(end);
   return t[0];
}

This function works well if you are trying to get the values between two values. For instance:

data='[value]insertdataherethatyouwanttoget[/value]';

If you were interested in getting the information from between the two [values] "tags", you could use the function like the following.

out=explode(data,'[value]','[/value]');
//Variable out would display the string: insertdataherethatyouwanttoget

But let's say you don't have those handy "tags" like the example above displayed. No matter.

out=explode(data,'insert','wanttoget');
//Now out would display the string: dataherethatyou

Wana see it in action? Click here.

How to echo in PHP, HTML tags

If you want to output large quantities of HTML you should consider using heredoc or nowdoc syntax. This will allow you to write your strings without the need for escaping.

echo <<<EOD
You can put "s and 's here if you like.
EOD;

Also note that because PHP is an embedded language you can add it between you HTML content and you don't need to echo any tags.

<div>
    <p>No PHP here!</p>
    <?php
    $name = "Marcel";
    echo "<p>Hello $name!</p>";
    ?>
</div>

Also if you just want to output a variable you should use the short-hand output tags <?=$var?>. This is equivalent to <?php echo $var; ?>.

How to get the first element of an array?

If your array is not guaranteed to be populated from index zero, you can use Array.prototype.find():

var elements = []
elements[1] = 'foo'
elements[2] = 'bar'

var first = function(element) { return !!element }    
var gotcha = elements.find(first)

console.log(a[0]) // undefined
console.log(gotcha) // 'foo'

What's the best way to add a full screen background image in React Native

import React, { Component } from 'react';
import { Image, StyleSheet } from 'react-native';

export default class App extends Component {
  render() {
    return (
      <Image source={{uri: 'http://i.imgur.com/IGlBYaC.jpg'}} style={s.backgroundImage} />
    );
  }
}

const s = StyleSheet.create({
  backgroundImage: {
      flex: 1,
      width: null,
      height: null,
  }
});

You can try it at: https://sketch.expo.io/B1EAShDie (from: github.com/Dorian/sketch-reactive-native-apps)

Docs: https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting

Apache Prefork vs Worker MPM

For CentOS 6.x and 7.x (including Amazon Linux) use:

sudo httpd -V

This will show you which of the MPMs are configured. Either prefork, worker, or event. Prefork is the earlier, threadsafe model. Worker is multi-threaded, and event supports php-mpm which is supposed to be a better system for handling threads and requests.

However, your results may vary, based on configuration. I've seen a lot of instability in php-mpm and not any speed improvements. An aggressive spider can exhaust the maximum child processes in php-mpm quite easily.

The setting for prefork, worker, or event is set in sudo nano /etc/httpd/conf.modules.d/00-mpm.conf (for CentOS 6.x/7.x/Apache 2.4).

# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#LoadModule mpm_worker_module modules/mod_mpm_worker.so

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#LoadModule mpm_event_module modules/mod_mpm_event.so

VirtualBox error "Failed to open a session for the virtual machine"

Updating VirtualBox to newest version fixed my issue.

Change form size at runtime in C#

In order to call this you will have to store a reference to your form and pass the reference to the run method. Then you can call this in an actionhandler.

public partial class Form1 : Form
{
    public void ChangeSize(int width, int height)
    {
        this.Size = new Size(width, height);
    }
}

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Can an int be null in Java?

Along with all above answer i would like to add this point too.

For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.

So by default we have,

   int a=0;

and not

   int a=null;

Same with other primitive types and hence null is only used for objects and not for primitive types.

How to set the title of UIButton as left alignment?

Swift 5.1

self.btnPro.titleLabel?.textAlignment = .left

Remove decimal values using SQL query

If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0). This will save you from replacing the ".00" characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation").

Othewise, you of course remove it using SQL query:

select replace(cast([height] as varchar), '.00', '') from table

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

You could use RAISE_APPLICATION_ERROR like this:

DECLARE
    ex_custom       EXCEPTION;
BEGIN
    RAISE ex_custom;
EXCEPTION
    WHEN ex_custom THEN
        RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/

That will raise an exception that looks like:

ORA-20001: My exception was raised

The error number can be anything between -20001 and -20999.

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

use grep -n -i null myfile.txt to output the line number in front of each match.

I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

grep -n -i null myfile.txt | wc -l

Python naming conventions for modules

nib is fine. If in doubt, refer to the Python style guide.

From PEP 8:

Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

TextView Marquee not working

android:focusable="true" and android:focusableInTouchMode="true" are essential....

Because I tested all others without these lines and the result was no marquee. When I add these it started to marquee..

How do I vertically align something inside a span tag?

I needed this for links, so I wrapped the span with an a-tag and a div, then centered the span tag itself

HTML

<div>
    <a class="tester" href="#">
        <span>Home</span>
    </a>
</div>

CSS

.tester{
    display: inline-block;
    width: 9em;
    height: 3em;
    text-align: center;
}
.tester>span{
    position: relative;
    top: 25%;
}

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Measuring execution time of a function in C++

simple program to find a function execution time taken.

#include <iostream>
#include <ctime> // time_t
#include <cstdio>

void function()
{
     for(long int i=0;i<1000000000;i++)
     {
        // do nothing
     }
}

int main()
{

time_t begin,end; // time_t is a datatype to store time values.

time (&begin); // note time before execution
function();
time (&end); // note time after execution

double difference = difftime (end,begin);
printf ("time taken for function() %.2lf seconds.\n", difference );

return 0;
}

Python Key Error=0 - Can't find Dict error in code

It only comes when your list or dictionary not available in the local function.

How to initialize java.util.date to empty

Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date. If you make it null means that it is not referring any instance of java.util.Date.

You have tried date2=""; what you mean to do by this statement you want to reference the instance of String to a variable that is suppose to store java.util.Date. This is not possible as Java is Strongly Typed Language.

Edit

After seeing the comment posted to the answer of LastFreeNickname

I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it

I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null as shown below:

if(textBox.getText() == null || textBox.getText().equals(""){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Also I can assume since you are asking user to enter a date in a TextBox, you are using a DateFormat to parse the text that is entered in the TextBox. If this is the case you could simply call the dateFormat.parse() which throws a ParseException if the format in which the date was written is incorrect or is empty string. Here in the catch block you could put the above statements as show below:

try{
    date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
    date2 = null; // For Null;
    // date2 = new Date(); For Current Date
    // date2 = new Date(0); For Default Date
}

Java: how can I split an ArrayList in multiple small ArrayLists?

I'm guessing that the issue you're having is with naming 100 ArrayLists and populating them. You can create an array of ArrayLists and populate each of those using a loop.

The simplest (read stupidest) way to do this is like this:

ArrayList results = new ArrayList(1000);
    // populate results here
    for (int i = 0; i < 1000; i++) {
        results.add(i);
    }
    ArrayList[] resultGroups = new ArrayList[100];
    // initialize all your small ArrayList groups
    for (int i = 0; i < 100; i++) {
            resultGroups[i] = new ArrayList();
    }
    // put your results into those arrays
    for (int i = 0; i < 1000; i++) {
       resultGroups[i/10].add(results.get(i));
    } 

EPPlus - Read Excel Table

Not sure why but none of the above solution work for me. So sharing what worked:

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
            }
        }
    }
}

How to select the first element with a specific attribute using XPath

The easiest way to find first english book node (in the whole document), taking under consideration more complicated structered xml file, like:

<bookstore>
 <category>
  <book location="US">A1</book>
  <book location="FIN">A2</book>
 </category>
 <category>
  <book location="FIN">B1</book>
  <book location="US">B2</book>
 </category>
</bookstore> 

is xpath expression:

/descendant::book[@location='US'][1]

port 8080 is already in use and no process using 8080 has been listed

Open eclipse go to Servers panel, right click or press F3 to open Overview window and go to Ports (Modify the server ports). You will get the following:

tomcat adminport
HTTP/1.1
AJP/1.3

You can change the port numbers (e.g. HTTP/1.1 port number 8080 to 8082).

Get content uri from file path in android

Its late, but may help someone in future.

To get content URI for a file, you may use the following method:

FileProvider.getUriForFile(Context context, String authority, File file)

It returns the content URI.

Check this out to learn how to setup a FileProvider

Mysql SELECT CASE WHEN something then return field

You are mixing the 2 different CASE syntaxes inappropriately.

Use this style (Searched)

  CASE  
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Or this style (Simple)

  CASE u.nnmu 
  WHEN '0' THEN mu.naziv_mesta
  WHEN '1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

Not This (Simple but with boolean search predicates)

  CASE u.nnmu 
  WHEN u.nnmu ='0' THEN mu.naziv_mesta
  WHEN u.nnmu ='1' THEN m.naziv_mesta
 ELSE 'GRESKA'
 END as mesto_utovara,

In MySQL this will end up testing whether u.nnmu is equal to the value of the boolean expression u.nnmu ='0' itself. Regardless of whether u.nnmu is 1 or 0 the result of the case expression itself will be 1

For example if nmu = '0' then (nnmu ='0') evaluates as true (1) and (nnmu ='1') evaluates as false (0). Substituting these into the case expression gives

 SELECT CASE  '0'
  WHEN 1 THEN '0'
  WHEN 0 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara

if nmu = '1' then (nnmu ='0') evaluates as false (0) and (nnmu ='1') evaluates as true (1). Substituting these into the case expression gives

 SELECT CASE  '1'
  WHEN 0 THEN '0'
  WHEN 1 THEN '1'
 ELSE 'GRESKA'
 END as mesto_utovara