Programs & Examples On #Rails agnostic

Bootstrap with jQuery Validation Plugin

For full compatibility with Bootstrap 3 I added support for input-group, radio and checkbox, that was missing in the other solutions.

Update 10/20/2017: Inspected suggestions of the other answers and added additional support for special markup of radio-inline, better error placement for a group of radios or checkboxes and added support for a custom .novalidation class to prevent validation of controls. Hope this helps and thanks for the suggestions.

After including the validation plugin add the following call:

$.validator.setDefaults({
    errorElement: "span",
    errorClass: "help-block",
    highlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        }
    },
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        }
        else if (element.prop('type') === 'radio' && element.parent('.radio-inline').length) {
            error.insertAfter(element.parent().parent());
        }
        else if (element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
            error.appendTo(element.parent().parent());
        }
        else {
            error.insertAfter(element);
        }
    }
});

This works for all Bootstrap 3 form classes. If you use a horizontal form you have to use the following markup. This ensures that the help-block text respects the validation states ("has-error", ...) of the form-group.

<div class="form-group">
    <div class="col-lg-12">
        <div class="checkbox">
            <label id="LabelConfirm" for="CheckBoxConfirm">
                <input type="checkbox" name="CheckBoxConfirm" id="CheckBoxConfirm" required="required" />
                I have read all the information 
            </label>
        </div>
    </div>
</div>

How to get $HOME directory of different user in bash script?

If the user doesn't exist, getent will return an error.

Here's a small shell function that doesn't ignore the exit code of getent:

get_home() {
  local result; result="$(getent passwd "$1")" || return
  echo $result | cut -d : -f 6
}

Here's a usage example:

da_home="$(get_home missing_user)" || {
  echo 'User does NOT exist!'; exit 1
}

# Now do something with $da_home
echo "Home directory is: '$da_home'"

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I was having the same problem , I have just copied the code to new project and started the build . Some other error started coming. error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead

To solve this problem again, I have added my one property in the Project project as below. Project -> Properties -> Configuration property -> c/c++ . In this category there is field name Preprocessor Definitions I have added _CRT_SECURE_NO_WARNINGS this to solve the problem Hope it will help ...

Thank You

Passing multiple variables to another page in url

Use the ampersand & to glue variables together:

$url = "http://localhost/main.php?email=$email_address&event_id=$event_id";
//                               ^ start of vars      ^next var

How to apply a function to two columns of Pandas dataframe

A simple solution is:

df['col_3'] = df[['col_1','col_2']].apply(lambda x: f(*x), axis=1)

"Continue" (to next iteration) on VBScript

I use to use the Do, Loop a lot but I have started using a Sub or a Function that I could exit out of instead. It just seemed cleaner to me. If any variables you need are not global you will need to pass them to the Sub also.

For i=1 to N
 DoWork i
Next

Sub DoWork(i)
    [Code]
    If Condition1 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [...]
End Sub

GIT clone repo across local file system in windows

I was successful in doing this using file://, but with one additional slash to denote an absolute path.

git clone file:///cygdrive/c/path/to/repository/

In my case I'm using Git on Cygwin for Windows, which you can see because of the /cygdrive/c part in my paths. With some tweaking to the path it should work with any git installation.

Adding a remote works the same way

git remote add remotename file:///cygdrive/c/path/to/repository/

How to get the month name in C#?

You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.

I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.

Here is an example of how to do it using extension methods:

using System;
using System.Globalization;

class Program
{
    static void Main()
    {

        Console.WriteLine(DateTime.Now.ToMonthName());
        Console.WriteLine(DateTime.Now.ToShortMonthName());
        Console.Read();
    }
}

static class DateTimeExtensions
{
    public static string ToMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
    }

    public static string ToShortMonthName(this DateTime dateTime)
    {
        return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
    }
}

Hope this helps!

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

writing a batch file that opens a chrome URL

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"

Using fonts with Rails asset pipeline

  1. If your Rails version is between > 3.1.0 and < 4, place your fonts in any of the these folders:

    • app/assets/fonts
    • lib/assets/fonts
    • vendor/assets/fonts


    For Rails versions > 4, you must place your fonts in the app/assets/fonts folder.

    Note: To place fonts outside of these designated folders, use the following configuration:

    config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/

    For Rails versions > 4.2, it is recommended to add this configuration to config/initializers/assets.rb.

    However, you can also add it to either config/application.rb , or to config/production.rb

  2. Declare your font in your CSS file:

    @font-face {
      font-family: 'Icomoon';
      src:url('icomoon.eot');
      src:url('icomoon.eot?#iefix') format('embedded-opentype'),
        url('icomoon.svg#icomoon') format('svg'),
        url('icomoon.woff') format('woff'),
        url('icomoon.ttf') format('truetype');
      font-weight: normal;
      font-style: normal;
    }
    

    Make sure your font is named exactly the same as in the URL portion of the declaration. Capital letters and punctuation marks matter. In this case, the font should have the name icomoon.

  3. If you are using Sass or Less with Rails > 3.1.0 (your CSS file has .scss or .less extension), then change the url(...) in the font declaration to font-url(...).

    Otherwise, your CSS file should have the extension .css.erb, and the font declaration should be url('<%= asset_path(...) %>').

    If you are using Rails > 3.2.1, you can use font_path(...) instead of asset_path(...). This helper does exactly the same thing but it's more clear.

  4. Finally, use your font in your CSS like you declared it in the font-family part. If it was declared capitalized, you can use it like this:

    font-family: 'Icomoon';
    

How to get UTF-8 working in Java webapps?

To add to kosoant's answer, if you are using Spring, rather than writing your own Servlet filter, you can use the class org.springframework.web.filter.CharacterEncodingFilter they provide, configuring it like the following in your web.xml:

 <filter>
    <filter-name>encoding-filter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
       <param-name>encoding</param-name>
       <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
       <param-name>forceEncoding</param-name>
       <param-value>FALSE</param-value>
    </init-param>
 </filter>
 <filter-mapping>
    <filter-name>encoding-filter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>

Are multi-line strings allowed in JSON?

Unfortunately many of the answers here address the question of how to put a newline character in the string data. The question is how to make the code look nicer by splitting the string value across multiple lines of code. (And even the answers that recognize this provide "solutions" that assume one is free to change the data representation, which in many cases one is not.)

And the worse news is, there is no good answer.

In many programming languages, even if they don't explicitly support splitting strings across lines, you can still use string concatenation to get the desired effect; and as long as the compiler isn't awful this is fine.

But json is not a programming language; it's just a data representation. You can't tell it to concatenate strings. Nor does its (fairly small) grammar include any facility for representing a string on multiple lines.

Short of devising a pre-processor of some kind (and I, for one, don't feel like effectively making up my own language to solve this issue), there isn't a general solution to this problem. IF you can change the data format, then you can substitute an array of strings. Otherwise, this is one of the numerous ways that json isn't designed for human-readability.

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

There's a nice way to eject webpack.config.js from angular-cli. Just run:

$ ng eject

This will generate webpack.config.js in the root folder of your project, and you're free to configure it the way you want. The downside of this is that build/start scripts in your package.json will be replaced with the new commands and instead of

$ ng serve

you would have to do something like

$ npm run build & npm run start

This method should work in all the recent versions of angular-cli (I personally tried a few, with the oldest being 1.0.0-beta.21, and the latest 1.0.0-beta.32.3)

Python not working in the command line of git bash

In addition to the answer of @Charles-Duffy, you can use winpty directly without installing/downloading anything extra. Just run winpty c:/Python27/python.exe. The utility winpty.exe can be found at Git\usr\bin. I'm using Git for Windows v2.7.1

The prebuilt binaries from @Charles-Duffy is version 0.1.1(according to the file name), while the included one is 0.2.2

how can the textbox width be reduced?

rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.

http://htmldog.com/reference/htmltags/textarea/

How can I add an image file into json object?

You will need to read the bytes from that File into a byte[] and put that object into your JSONObject.

You should also have a look at the following posts :

Hope this helps.

dynamically set iframe src

Try this:

document.frames["myiframe"].onload = function(){
   alert("Hello World");
}

List distinct values in a vector in R

Do you mean unique:

R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4

How to download a file over HTTP?

urlretrieve and requests.get are simple, however the reality not. I have fetched data for couple sites, including text and images, the above two probably solve most of the tasks. but for a more universal solution I suggest the use of urlopen. As it is included in Python 3 standard library, your code could run on any machine that run Python 3 without pre-installing site-package

import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)

#remember to open file in bytes mode
with open(filename, 'wb') as f:
    while True:
        buffer = url_connect.read(buffer_size)
        if not buffer: break

        #an integer value of size of written data
        data_wrote = f.write(buffer)

#you could probably use with-open-as manner
url_connect.close()

This answer provides a solution to HTTP 403 Forbidden when downloading file over http using Python. I have tried only requests and urllib modules, the other module may provide something better, but this is the one I used to solve most of the problems.

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

If you can not authenticate via the web interface (localhost/phpmyadmin/) then try change authentication type to cookie.

$cfg['Servers'][$i]['auth_type'] = 'cookie';

Validating Phone Numbers Using Javascript

<html>
<title>Practice Session</title>
<body>           
<form name="RegForm" onsubmit="return validate()" method="post">  
<p>Name: <input type="text" name="Name"> </p><br>        
<p>Contact: <input type="text" name="Telephone"> </p><br>   
<p><input type="submit" value="send" name="Submit"></p>          
</form> 
</body>
<script> 
function validate()                                    
{ 
var name = document.forms["RegForm"]["Name"];                
var phone = document.forms["RegForm"]["Telephone"];  
if (name.value == "")                                  
{ 
window.alert("Please enter your name."); 
name.focus();
return false;
}
else if(isNaN(name.value) /*"%d[10]"*/)
{
alert("name confirmed");
}
else{ 
window.alert("please enter character"); 
}   
if (phone.value == "")                           
{ 
window.alert("Please enter your telephone number."); 
phone.focus();
return false; 
} 
else if(!isNaN(phone.value) /*phone.value == isNaN(phone.value)*/)
{
alert("number confirmed");
}
else{
window.alert("please enter numbers only");
}   
}
</script> 
</html>

How to get page content using cURL?

For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again. Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)

  $url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

How to show two figures using matplotlib?

Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()

In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

LINQ Aggregate algorithm explained

Aggregate is basically used to Group or Sum up data.

According to MSDN "Aggregate Function Applies an accumulator function over a sequence."

Example 1: Add all the numbers in a array.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate((total, nextValue) => total + nextValue);

*important: The initial aggregate value by default is the 1 element in the sequence of collection. i.e: the total variable initial value will be 1 by default.

variable explanation

total: it will hold the sum up value(aggregated value) returned by the func.

nextValue: it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Example 2: Add all items in an array. Also set the initial accumulator value to start adding with from 10.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate(10, (total, nextValue) => total + nextValue);

arguments explanation:

the first argument is the initial(starting value i.e seed value) which will be used to start addition with the next value in the array.

the second argument is a func which is a func that takes 2 int.

1.total: this will hold same as before the sum up value(aggregated value) returned by the func after the calculation.

2.nextValue: : it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Also debugging this code will give you a better understanding of how aggregate work.

How do I run git log to see changes only for a specific branch?

The problem I was having, which I think is similar to this, is that master was too far ahead of my branch point for the history to be useful. (Navigating to the branch point would take too long.)

After some trial and error, this gave me roughly what I wanted:

git log --graph --decorate --oneline --all ^master^!

Multiple returns from a function

You can get the values of two or more variables by setting them by reference:

function t(&$a, &$b) {
    $a = 1;
    $b = 2;
}


t($a, $b);

echo $a . '  ' . $b;

Output:

1 2

How can I capitalize the first letter of each word in a string?

Don't overlook the preservation of white space. If you want to process 'fred flinstone' and you get 'Fred Flinstone' instead of 'Fred Flinstone', you've corrupted your white space. Some of the above solutions will lose white space. Here's a solution that's good for Python 2 and 3 and preserves white space.

def propercase(s):
    return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

Get full query string in C# ASP.NET

This should work fine for you.

Write this code in the Page_Load event of the page.

string ID = Request.QueryString["id"].ToString();
Response.Redirect("http://www.example.com/rendernews.php?id=" + ID);

split python source code into multiple files?

Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:

>>> from test import disp
>>> disp('World!')

Or with a namespace:

>>> import test
>>> test.disp('World!')

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

jQuery/Javascript function to clear all the fields of a form

    <form id="form" method="post" action="action.php">
      <input type="text" class="removeLater" name="name" /> Username<br/>
      <input type="text" class="removeLater" name="pass" /> Password<br/>
      <input type="text" class="removeLater" name="pass2" /> Password again<br/>
    </form>
    <script>
$(function(){
    $("form").submit(function(e){
         //do anything you want
         //& remove values
         $(".removeLater").val('');
    }

});
</script>

Show week number with Javascript?

In case you already use jquery-ui (specifically datepicker):

Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }

Usage:

var myDate = new Date();
myDate.getWeek();

More here: UI/Datepicker/iso8601Week

I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jquery-ui this might just be a simple fit for someone - as it was for me.

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Go to..

File > Settings > Appearance & Behavior > System Settings > HTTP Proxy Enable following option Auto-detect proxy settings

and press checkConnection button for test

Show "loading" animation on button click

$("#btnId").click(function(e){
      e.preventDefault();
      $.ajax({
        ...
        beforeSend : function(xhr, opts){
            //show loading gif
        },
        success: function(){

        },
        complete : function() {
           //remove loading gif
        }
    });
});

How to add message box with 'OK' button?

@Override
protected Dialog onCreateDialog(int id)
{
    switch(id)
    {
    case 0:
    {               
        return new AlertDialog.Builder(this)
        .setMessage("text here")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {                   
            @Override
            public void onClick(DialogInterface arg0, int arg1) 
            {
                try
                {

                }//end try
                catch(Exception e)
                {
                    Toast.makeText(getBaseContext(),  "", Toast.LENGTH_LONG).show();
                }//end catch
            }//end onClick()
        }).create();                
    }//end case
  }//end switch
    return null;
}//end onCreateDialog

How to finish current activity in Android

What I was doing was starting a new activity and then closing the current activity. So, remember this simple rule:

finish()
startActivity<...>()

and not

startActivity<...>()
finish()

How to get column values in one comma separated value

SELECT name, GROUP_CONCAT( section ) 
FROM  `tmp` 
GROUP BY name

How to capture UIView to UIImage without loss of quality on retina display

Swift 2.0:

Using extension method:

extension UIImage{

   class func renderUIViewToImage(viewToBeRendered:UIView?) -> UIImage
   {
       UIGraphicsBeginImageContextWithOptions((viewToBeRendered?.bounds.size)!, false, 0.0)
       viewToBeRendered!.drawViewHierarchyInRect(viewToBeRendered!.bounds, afterScreenUpdates: true)
       viewToBeRendered!.layer.renderInContext(UIGraphicsGetCurrentContext()!)

       let finalImage = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()

       return finalImage
   }

}

Usage:

override func viewDidLoad() {
    super.viewDidLoad()

    //Sample View To Self.view
    let sampleView = UIView(frame: CGRectMake(100,100,200,200))
    sampleView.backgroundColor =  UIColor(patternImage: UIImage(named: "ic_120x120")!)
    self.view.addSubview(sampleView)    

    //ImageView With Image
    let sampleImageView = UIImageView(frame: CGRectMake(100,400,200,200))

    //sampleView is rendered to sampleImage
    var sampleImage = UIImage.renderUIViewToImage(sampleView)

    sampleImageView.image = sampleImage
    self.view.addSubview(sampleImageView)

 }

DB2 Query to retrieve all table names for a given schema

Using the DB2 commands (no SQL) there is the possibility of executing

db2 LIST TABLES FOR ALL

This shows all the tables in all the schemas in the database.

ref: show all tables in DB2 using the LIST command

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

CSS3 gradient background set on body doesn't stretch but instead repeats?

I know I'm late to the party, but here's a more solid answer.

All you need to do is use min-height: 100%; rather than height: 100%; and your gradient background will extend the entire height of the viewport without repeating, even if the content is scrollable.

Like this:

html {
    min-height: 100%;
}

body {
    background: linear-gradient(#ff7241, #ff4a1f);
}

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

Cannot implicitly convert type 'int' to 'short'

The result of summing two Int16 variables is an Int32:

Int16 i1 = 1;
Int16 i2 = 2;
var result = i1 + i2;
Console.WriteLine(result.GetType().Name);

It outputs Int32.

Adding a background image to a <div> element

<div id="image">Example to have Background Image</div>

We need to Add the below content in Style tag:

.image {
  background-image: url('C:\Users\ajai\Desktop\10.jpg');
}

How to display pdf in php

Simple way to display pdf files from database and we can download it.
$resume is pdf file name which comes from database.
../resume/filename is path of folder where your file is stored.

<a href="../resumes/<?php echo $resume; ?>"/><?php echo $resume; ?></a>

How To Use DateTimePicker In WPF?

I don't think this DateTimePicker has been mentioned before:

A WPF DateTimePicker That Works Like the One in Winforms

That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.

DateTimePicker

Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.

How to display an error message in an ASP.NET Web Application

All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.

If occurs during a postback: markup:

<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>

code:

try
{
do something
}

catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

default web page width - 1024px or 980px?

This is a bit of an open ended question since screen sizes are changing all the time and what might have been correct two years ago would likely be out of date now.

I use Twitter Bootstrap 3 at present and it uses a fluid grid system designed to work at sizes ranging from mobile/very small all the way up to the huge wide screen monitors that are now available.

Currently the upper default in BS3 is 1200px which translates to a container width of 1144px after taking account of margins and padding of the grids elements.

In my experience, modern designers are working to a width of around 1366px for desktop. All recent designs I've been given to implement have been 1366px.

Note also that you can customise the BS3 grid quite heavily. For example we will use a 32 column grid with 4px gutter in our sites/designs going forwards.

Ultimately the decision on page width needs to be made based on your website analytics and the screen sizes that your visitors typically use.

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

to

"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

How to make sure you don't get WCF Faulted state exception?

If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.

Return from lambda forEach() in java

The return there is returning from the lambda expression rather than from the containing method. Instead of forEach you need to filter the stream:

players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.

This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.

How to store an array into mysql?

Consider normalizing the table structure into a comments, and a separate votes table.

Table "comments":

id
comment
user
...

Table "votes":

user_id  
comment_id
vote (downvote/upvote)

this would allow an unlimited number of votes without having to deal with the limits of a database field.

Also, you may have future needs for operations like "show all votes a user has cast", removing specific votes or limiting the maximum number of votes per day. These operations are dead easy and fast to implement with a normalized structure, and horribly slow and complex in a serialized array.

Vue.js getting an element within a component

vuejs 2

v-el:el:uniquename has been replaced by ref="uniqueName". The element is then accessed through this.$refs.uniqueName.

Using the "start" command with parameters passed to the started program

The spaces are DOSs/CMDs Problems so you should go to the Path via:

cd "c:\program files\Microsoft Virtual PC"

and then simply start VPC via:

start Virtual~1.exe -pc MY-PC -launch

~1 means the first exe with "Virtual" at the beginning. So if there is a "Virtual PC.exe" and a "Virtual PC1.exe" the first would be the Virtual~1.exe and the second Virtual~2.exe and so on.

Or use a VNC-Client like VirtualBox.

Create a file if one doesn't exist - C

If fptr is NULL, then you don't have an open file. Therefore, you can't freopen it, you should just fopen it.

FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
    fptr = fopen("scores.dat", "wb");
}

note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.

A complete example

int main()
{
    FILE *fptr;
    char there_was_error = 0;
    char opened_in_read  = 1;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        opened_in_read = 0;
        fptr = fopen("scores.dat", "wb");
        if (fptr == NULL)
            there_was_error = 1;
    }
    if (there_was_error)
    {
        printf("Disc full or no permission\n");
        return EXIT_FAILURE;
    }
    if (opened_in_read)
        printf("The file is opened in read mode."
               " Let's read some cached data\n");
    else
        printf("The file is opened in write mode."
               " Let's do some processing and cache the results\n");
    return EXIT_SUCCESS;
}

ASP.Net which user account running Web Service on IIS 7?

Server 2008

Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.

In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity

Here's the info from Microsoft on setting up Application Pool Identites:

http://learn.iis.net/page.aspx/624/application-pool-identities/

Java - Including variables within strings?

You can always use String.format(....). i.e.,

String string = String.format("A String %s %2d", aStringVar, anIntVar);

I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.

All shards failed

If you encounter this apparent index corruption in a running system, you can work around it by deleting all files called segments.gen. It is advisory only, and Lucene can recover correctly without it.

From ElasticSearch Blog

How to run functions in parallel?

Seems like you have a single function that you need to call on two different parameters. This can be elegantly done using a combination of concurrent.futures and map with Python 3.2+

import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

def sleep_secs(seconds):
  time.sleep(seconds)
  print(f'{seconds} has been processed')

secs_list = [2,4, 6, 8, 10, 12]

Now, if your operation is IO bound, then you can use the ThreadPoolExecutor as such:

with ThreadPoolExecutor() as executor:
  results = executor.map(sleep_secs, secs_list)

Note how map is used here to map your function to the list of arguments.

Now, If your function is CPU bound, then you can use ProcessPoolExecutor

with ProcessPoolExecutor() as executor:
  results = executor.map(sleep_secs, secs_list)

If you are not sure, you can simply try both and see which one gives you better results.

Finally, if you are looking to print out your results, you can simply do this:

with ThreadPoolExecutor() as executor:
  results = executor.map(sleep_secs, secs_list)
  for result in results:
    print(result)

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

Windows equivalent of $export

To translate your *nix style command script to windows/command batch style it would go like this:

SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"

mkdir on windows doens't have a -p parameter : from the MKDIR /? help:

MKDIR creates any intermediate directories in the path, if needed.

which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide

How to convert from []byte to int in Go Programming

Starting from a byte array you can use the binary package to do the conversions.

For example if you want to read ints :

buf := bytes.NewBuffer(b) // b is []byte
myfirstint, err := binary.ReadVarint(buf)
anotherint, err := binary.ReadVarint(buf)

The same package allows the reading of unsigned int or floats, with the desired byte orders, using the general Read function.

Seedable JavaScript random number generator

If you program in Typescript, I adapted the Mersenne Twister implementation that was brought in Christoph Henkelmann's answer to this thread as a typescript class:

/**
 * copied almost directly from Mersenne Twister implementation found in https://gist.github.com/banksean/300494
 * all rights reserved to him.
 */
export class Random {
    static N = 624;
    static M = 397;
    static MATRIX_A = 0x9908b0df;
    /* constant vector a */
    static UPPER_MASK = 0x80000000;
    /* most significant w-r bits */
    static LOWER_MASK = 0x7fffffff;
    /* least significant r bits */

    mt = new Array(Random.N);
    /* the array for the state vector */
    mti = Random.N + 1;
    /* mti==N+1 means mt[N] is not initialized */

    constructor(seed:number = null) {
        if (seed == null) {
            seed = new Date().getTime();
        }

        this.init_genrand(seed);
    }

    private init_genrand(s:number) {
        this.mt[0] = s >>> 0;
        for (this.mti = 1; this.mti < Random.N; this.mti++) {
            var s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);
            this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
                + this.mti;
            /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
            /* In the previous versions, MSBs of the seed affect   */
            /* only MSBs of the array mt[].                        */
            /* 2002/01/09 modified by Makoto Matsumoto             */
            this.mt[this.mti] >>>= 0;
            /* for >32 bit machines */
        }
    }

    /**
     * generates a random number on [0,0xffffffff]-interval
     * @private
     */
    private _nextInt32():number {
        var y:number;
        var mag01 = new Array(0x0, Random.MATRIX_A);
        /* mag01[x] = x * MATRIX_A  for x=0,1 */

        if (this.mti >= Random.N) { /* generate N words at one time */
            var kk:number;

            if (this.mti == Random.N + 1)   /* if init_genrand() has not been called, */
                this.init_genrand(5489);
            /* a default initial seed is used */

            for (kk = 0; kk < Random.N - Random.M; kk++) {
                y = (this.mt[kk] & Random.UPPER_MASK) | (this.mt[kk + 1] & Random.LOWER_MASK);
                this.mt[kk] = this.mt[kk + Random.M] ^ (y >>> 1) ^ mag01[y & 0x1];
            }
            for (; kk < Random.N - 1; kk++) {
                y = (this.mt[kk] & Random.UPPER_MASK) | (this.mt[kk + 1] & Random.LOWER_MASK);
                this.mt[kk] = this.mt[kk + (Random.M - Random.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
            }
            y = (this.mt[Random.N - 1] & Random.UPPER_MASK) | (this.mt[0] & Random.LOWER_MASK);
            this.mt[Random.N - 1] = this.mt[Random.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1];

            this.mti = 0;
        }

        y = this.mt[this.mti++];

        /* Tempering */
        y ^= (y >>> 11);
        y ^= (y << 7) & 0x9d2c5680;
        y ^= (y << 15) & 0xefc60000;
        y ^= (y >>> 18);

        return y >>> 0;
    }

    /**
     * generates an int32 pseudo random number
     * @param range: an optional [from, to] range, if not specified the result will be in range [0,0xffffffff]
     * @return {number}
     */
    nextInt32(range:[number, number] = null):number {
        var result = this._nextInt32();
        if (range == null) {
            return result;
        }

        return (result % (range[1] - range[0])) + range[0];
    }

    /**
     * generates a random number on [0,0x7fffffff]-interval
     */
    nextInt31():number {
        return (this._nextInt32() >>> 1);
    }

    /**
     * generates a random number on [0,1]-real-interval
     */
    nextNumber():number {
        return this._nextInt32() * (1.0 / 4294967295.0);
    }

    /**
     * generates a random number on [0,1) with 53-bit resolution
     */
    nextNumber53():number {
        var a = this._nextInt32() >>> 5, b = this._nextInt32() >>> 6;
        return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
    }
}

you can than use it as follows:

var random = new Random(132);
random.nextInt32(); //return a pseudo random int32 number
random.nextInt32([10,20]); //return a pseudo random int in range [10,20]
random.nextNumber(); //return a a pseudo random number in range [0,1]

check the source for more methods.

How to apply !important using .css()?

After reading other answers and experimenting, this is what works for me:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );

This doesn't work in IE 8 and under, though.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

How to set Android camera orientation properly?

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:

Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.

The method:

    protected void setDisplayOrientation(Camera camera, int angle){
    Method downPolymorphic;
    try
    {
        downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
        if (downPolymorphic != null)
            downPolymorphic.invoke(camera, new Object[] { angle });
    }
    catch (Exception e1)
    {
    }
}

And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :

    if (Integer.parseInt(Build.VERSION.SDK) >= 8)
        setDisplayOrientation(mCamera, 90);
    else
    {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation", 90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }
    }   

Easy way to make a confirmation dialog in Angular?

you can use window.confirm inside your function combined with if condition

 delete(whatever:any){
    if(window.confirm('Are sure you want to delete this item ?')){
    //put your delete method logic here
   }
}

when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.

What is the difference between the HashMap and Map objects in Java?

Map is interface and Hashmap is a class that implements Map Interface

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

To keep the accordion nature intact when wanting to also use 'hide' and 'show' functions like .collapse( 'hide' ), you must initialize the collapsible panels with the parent property set in the object with toggle: false before making any calls to 'hide' or 'show'

// initialize collapsible panels
$('#accordion .collapse').collapse({
  toggle: false,
  parent: '#accordion'
});

// show panel one (will collapse others in accordion)
$( '#collapseOne' ).collapse( 'show' );

// show panel two (will collapse others in accordion)
$( '#collapseTwo' ).collapse( 'show' );

// hide panel two (will not collapse/expand others in accordion)
$( '#collapseTwo' ).collapse( 'hide' );

Returning data from Axios API

IMO extremely important rule of thumb for your client side js code is to keep separated the data handling and ui building logic into different funcs, which is also valid for axios data fetching ... in this way your control flow and error handlings will be much more simple and easier to manage, as it could be seen from this ok fetch

and this NOK fetch

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

       function getUrlParams (){
          var url_params = new URLSearchParams();
          if( window.location.toString().indexOf("?") != -1) {
             var href_part = window.location.search.split('?')[1]
             href_part.replace(/([^=&]+)=([^&]*)/g,
                function(m, key, value) {
                   var attr = decodeURIComponent(key)
                   var val = decodeURIComponent(value)
                   url_params.append(attr,val);
             });
          }
          // for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
          return url_params ;
       }


      function getServerData (url, urlParams ){
          if ( typeof url_params == "undefined" ) { urlParams = getUrlParams()  }
          return axios.get(url , { params: urlParams } )
          .then(response => {
             return response ;
          })
          .catch(function(error) {
             console.error ( error )
             return error.response;
          })
       }

    // Action !!!
    getServerData(url , url_params)
        .then( response => {
           if ( response.status === 204 ) {
              var warningMsg = response.statusText
              console.warn ( warningMsg )
              return
           } else if ( response.status === 404 || response.status === 400) {
              var errorMsg = response.statusText // + ": "  + response.data.msg // this is my api
              console.error( errorMsg )
              return ;
           } else {
              var data = response.data
              var dataType = (typeof data)
              if ( dataType === 'undefined' ) {
                 var msg = 'unexpected error occurred while fetching data !!!'
                 // pass here to the ui change method the msg aka
                 // showMyMsg ( msg , "error")
              } else {
                 var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
                 // call here the ui building method
                 // BuildList ( items )
              }
              return
           }

        })




    </script>

Mysql select distinct

You can use DISTINCT like that

mysql_query("SELECT DISTINCT(ticket_id), column1, column2, column3 
FROM temp_tickets 
ORDER BY ticket_id");

How to replace local branch with remote branch entirely in Git?

git checkout .

i always use this command to replace my local changes with repository changes. git checkout space dot.

Does MS SQL Server's "between" include the range boundaries?

I've always used this:

WHERE myDate BETWEEN startDate AND (endDate+1)

What file uses .md extension and how should I edit them?

Markdown is a plain-text file format. The extensions .md and .markdown are just text files written in Markdown syntax. If you have a Readme.md in your repo, GitHub will show the contents on the home page of your repo. Read the documentation:

You can edit the Readme.md file in GitHub itself. Click on Readme.md, you will find an edit button. You can preview your changes and even commit them from there.

Since it is a text file, Notepad or Notepad++ (Windows), TextEdit (Mac) or any other text editor can be used to edit and modify it. Specialized editors exist that automatically parse the markdown as you type it and generate a preview, while others apply various syntax coloring and decorations to the displayed text. In both cases though, the saved file is still a readable text file.

If you want to create an md file with preview and if you prefer not to install any special editors, you can use online editors like dillinger.io and stackedit.io. They provide live preview. You can also export your files to Google Drive or Dropbox.

json parsing error syntax error unexpected end of input

This error occurs on an empty JSON file reading.

To avoid this error in NodeJS I'm checking the file's size:

const { size } = fs.statSync(JSON_FILE);
const content = size ? JSON.parse(fs.readFileSync(JSON_FILE)) : DEFAULT_VALUE;

Pass values of checkBox to controller action in asp.net mvc4

If you want your value to be read by MVT controller when you submit the form and you don't what to deal with hidden inputs. What you can do is add value attribute to your checkbox and set it to true or false.

MVT will not recognize viewModel property myCheckbox as true here

<input type="checkbox" name="myCheckbox" checked="checked" />

but will if you add

<input type="checkbox" name="myCheckbox" checked="checked" value="true" />

Script that does it:

$(document).on("click", "[type='checkbox']", function(e) {
        if (this.checked) {
            $(this).attr("value", "true");
        } else {
            $(this).attr("value","false");}
    });

What is the difference between procedural programming and functional programming?

Procedural languages tend to keep track of state (using variables) and tend to execute as a sequence of steps. Purely functional languages don't keep track of state, use immutable values, and tend to execute as a series of dependencies. In many cases the status of the call stack will hold the information that would be equivalent to that which would be stored in state variables in procedural code.

Recursion is a classic example of functional style programming.

Fastest method to replace all instances of a character in a string

I tried a number of these suggestions after realizing that an implementation I had written of this probably close to 10 years ago actually didn't work completely (nasty production bug in an long-forgotten system, isn't that always the way?!)... what I noticed is that the ones I tried (I didn't try them all) had the same problem as mine, that is, they wouldn't replace EVERY occurrence, only the first, at least for my test case of getting "test....txt" down to "test.txt" by replacing ".." with "."... maybe I missed so regex situation? But I digress...

So, I rewrote my implementation as follows. It's pretty darned simple, although I suspect not the fastest but I also don't think the difference will matter with modern JS engines, unless you're doing this inside a tight loop of course, but that's always the case for anything...

function replaceSubstring(inSource, inToReplace, inReplaceWith) {

  var outString = inSource;
  while (true) {
    var idx = outString.indexOf(inToReplace);
    if (idx == -1) {
      break;
    }
    outString = outString.substring(0, idx) + inReplaceWith +
      outString.substring(idx + inToReplace.length);
  }
  return outString;

}

Hope that helps someone!

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How to make an inline-block element fill the remainder of the line?

You can use calc (100% - 100px) on the fluid element, along with display:inline-block for both elements.

Be aware that there should not be any space between the tags, otherwise you will have to consider that space in your calc too.

.left{
    display:inline-block;
    width:100px;
}
.right{
    display:inline-block;
    width:calc(100% - 100px);
}


<div class=“left”></div><div class=“right”></div>

Quick example: http://jsfiddle.net/dw689mt4/1/

How to allow only numbers in textbox in mvc4 razor

Hi try the following....

<div class="editor-field">
  <%: Html.TextBoxFor(m => m.UserName, new {onkeydown="return ValidateNumber(event);" })%>
  <%: Html.ValidationMessageFor(m => m.UserName) %>
</div>

SCRIPT

<script type="text/javascript">
   function ValidateNumber(e) {
       var evt = (e) ? e : window.event;
       var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
       if (charCode > 31 && (charCode < 48 || charCode > 57)) {
           return false;
       }
       return true;
   };

How do I limit the number of rows returned by an Oracle query after ordering?

I'v started preparing for Oracle 1z0-047 exam, validated against 12c While prepping for it i came across a 12c enhancement known as 'FETCH FIRST' It enables you to fetch rows /limit rows as per your convenience. Several options are available with it

- FETCH FIRST n ROWS ONLY
 - OFFSET n ROWS FETCH NEXT N1 ROWS ONLY // leave the n rows and display next N1 rows
 - n % rows via FETCH FIRST N PERCENT ROWS ONLY

Example:

Select * from XYZ a
order by a.pqr
FETCH FIRST 10 ROWS ONLY

html5 input for money/currency

Enabling Fractions/Cents/Decimals for Number Input

In order to allow fractions (cents) on an HTML5 number input, you need to specify the "step" attribute to = "any":

<input type="number" min="1" step="any" />

This will specifically keep Chrome from displaying an error when a decimal/fractional currency is entered into the input. Mozilla, IE, etc... don't error out if you forget to specify step="any". W3C spec states that step="any" should, indeed, be needed to allow for decimals. So, you should definitely use it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step

Note that if you want the up/down buttons to do a specific granularity, then you must specify a numeric step such as ".01".

Also, the number input is now pretty widely supported (>90% of users).


What Input Options are there for Money/Currency?

The title of the question has since changed and takes on a slightly different meaning. One could use both number or text input in order to accept money/decimals.

For an input field for currency/money, it is recommended to use input type of number and specify appropriate attributes as outlined above. As of 2020, there is not a W3C spec for an actual input type of currency or money.

Main reason being it automatically coerces the users into entering a valid standard currency format and disallows any alphanumeric text. With that said, you could certainly use the regular text input and do some post processing to only grab the numeric/decimal value (there should be server side validation on this at some point as well).

The OP detailed a requirement of currency symbols and commas. If you want fancier logic/formatting like that, (as of 2020) you'll need to create custom JS logic for a text input or find a plugin.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I also had a similar issue. After copying and pasting to a sheet I wanted the cursor/ selected cell to be A1 not the range that I just pasted into.

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet("A1").Select

but got a 400 error which was actually a 1004 error

You need to activate the sheet before changing the selected cell this worked

Dim wkSheet as Worksheet
Set wkSheet = Worksheets(<sheetname>)

wkSheet.Activate
wkSheet("A1").Select

Getting the screen resolution using PHP

<script type="text/javascript">

if(screen.width <= 699){
    <?php $screen = 'mobile';?>
}else{
    <?php $screen = 'default';?>
}

</script>

<?php echo $screen; ?> 

How to build a DataTable from a DataGridView?

one of best solution enjoyed it ;)

  public DataTable GetContentAsDataTable(bool IgnoreHideColumns=false)
        {
            try
            {
                if (dgv.ColumnCount == 0) return null;
                DataTable dtSource = new DataTable();
                foreach (DataGridViewColumn col in dgv.Columns)
                {
                    if (IgnoreHideColumns & !col.Visible) continue;
                    if (col.Name == string.Empty) continue;
                    dtSource.Columns.Add(col.Name, col.ValueType);
                    dtSource.Columns[col.Name].Caption = col.HeaderText;
                }
                if (dtSource.Columns.Count == 0) return null;
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    DataRow drNewRow = dtSource.NewRow();
                    foreach (DataColumn  col in dtSource .Columns)
                    {
                        drNewRow[col.ColumnName] = row.Cells[col.ColumnName].Value;
                    }
                    dtSource.Rows.Add(drNewRow);
                }
                return dtSource;
            }
            catch { return null; }
        }

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

How to store arbitrary data for some HTML tags

Just another way, I personally wouldn't use this but it works (assure your JSON is valid because eval() is dangerous).

<a class="article" href="link/for/non-js-users.html">
    <span style="display: none;">{"id": 1, "title":"Something"}</span>
    Text of Link
</a>

// javascript
var article = document.getElementsByClassName("article")[0];
var data = eval(article.childNodes[0].innerHTML);

Why is my asynchronous function returning Promise { <pending> } instead of a value?

The then method returns a pending promise which can be resolved asynchronously by the return value of a result handler registered in the call to then, or rejected by throwing an error inside the handler called.

So calling AuthUser will not suddenly log the user in synchronously, but returns a promise whose then registered handlers will be called after the login succeeds ( or fails). I would suggest triggering all login processing by a then clause of the login promise. E.G. using named functions to highlight the sequence of flow:

let AuthUser = data => {   // just the login promise
  return google.login(data.username, data.password);
};

AuthUser(data).then( processLogin).catch(loginFail);

function processLogin( token) {
      // do logged in stuff:
      // enable, initiate, or do things after login
}
function loginFail( err) {
      console.log("login failed: " + err);
}

Get HTML code using JavaScript with a URL

Edit: doesnt work yet...

Add this to your JS:

var src = fetch('https://page.com')

It saves the source of page.com to variable 'src'

Twitter Bootstrap Multilevel Dropdown Menu

I just added class="span2" to the <li> for the dropdown items and that worked.

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

try the following to change your array to 1D

a.reshape((1, -1))

Make a td fixed size (width,height) while rest of td's can expand

just set the width of the td/column you want to be fixed and the rest will expand.

<td width="200"></td>

Oracle: how to set user password unexpire?

While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE

Let check the parameter value.
If in Case it is :

SQL> show parameter resource_limit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ---------
resource_limit                       boolean     FALSE
Its mean resource limit is off,we ist have to enable it. 

Use the ALTER SYSTEM statement to turn on resource limits. 

SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

Call break in nested if statements

To make multiple checking statements more readable (and avoid nested ifs):

var tmp = 'Test[[email protected]]';

var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;

do {
    if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }

    posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
    posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');

    if (posStartEmail === -1 || posEndEmail === -1) { break; }

    email = tmp.substring(posStartEmail+1+4,posEndEmail);

    if (email.indexOf('@') === -1) { break; }

// all checks are done - do what you intend to do

    alert ('All checks are ok')

    break; // the most important break of them all

} while(true);

How do you completely remove Ionic and Cordova installation from mac?

If you want to delete ionic and cordova at same time.Run this code in cmd

npm uninstall -g ionic cordova

Hide a EditText & make it visible by clicking a menu

Try phoneNumber.setVisibility(View.GONE);

How to run a Command Prompt command with Visual Basic code?

Or, you could do it the really simple way.

Dim OpenCMD 
OpenCMD = CreateObject("wscript.shell")
OpenCMD.run("Command Goes Here")

c# datagridview doubleclick on row with FullRowSelect

In CellContentDoubleClick event fires only when double clicking on cell's content. I used this and works:

    private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(e.RowIndex.ToString());
    }

Div table-cell vertical align not working

Sometime floats brake the vertical align, is better to avoid them.

How to change Java version used by TOMCAT?

test open the termenal or cmd. go to the [tomcat-home]\bin directory. ex: c:\tomcat8\bin write the following command: Tomcat8W //ES//Tomcat8 will open dialog, select the java tap(top tap). change the Java virtual Machine value.

How to include view/partial specific styling in AngularJS

Could append a new stylesheet to head within $routeProvider. For simplicity am using a string but could create new link element also, or create a service for stylesheets

/* check if already exists first - note ID used on link element*/
/* could also track within scope object*/
if( !angular.element('link#myViewName').length){
    angular.element('head').append('<link id="myViewName" href="myViewName.css" rel="stylesheet">');
}

Biggest benefit of prelaoding in page is any background images will already exist, and less lieklyhood of FOUC

Push commits to another branch

In my case I had one local commit, which wasn't pushed to origin\master, but commited to my local master branch. This local commit should be now pushed to another branch.

With Git Extensions you can do something like this:

  • (Create if not existing and) checkout new branch, where you want to push your commit.
  • Select the commit from the history, which should get commited & pushed to this branch.
  • Right click and select Cherry pick commit.
  • Press Cherry pick button afterwards.
  • The selected commit get's applied to your checked out branch. Now commit and push it.
  • Check out your old branch, with the faulty commit.
  • Hard reset this branch to the second last commit, where everything was ok (be aware what are you doing here!). You can do that via right click on the second last commit and select Reset current branch to here. Confirm the opperation, if you know what you are doing.

You could also do that on the GIT command line. Example copied from David Christensen:

I think you'll find git cherry-pick + git reset to be a much quicker workflow:

Using your same scenario, with "feature" being the branch with the top-most commit being incorrect, it'd be much easier to do this:

git checkout master
git cherry-pick feature
git checkout feature
git reset --hard HEAD^

Saves quite a bit of work, and is the scenario that git cherry-pick was designed to handle.

I'll also note that this will work as well if it's not the topmost commit; you just need a commitish for the argument to cherry-pick, via:

git checkout master
git cherry-pick $sha1
git checkout feature
git rebase -i ... # whack the specific commit from the history

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

So In my case, After trying all the above options, I realized it was VPN (company firewall).once connected and ran cmd: clean install spring-boot:run. Issue is resolved. Step 1: check maven is configured correctly or not. Step 2: check settings.xml is mapped correctly or not. Step 3: verify if you are behind any firewall then map your repo urls accordingly. Step 4:run clean install spring-boot:run step 5: issue is resolved.

Linux: where are environment variables stored?

That variable isn't stored in some script. It's simply set by the X server scripts. You can check the environment variables currently set using set.

offsetTop vs. jQuery.offset().top

This is what jQuery API Doc says about .offset():

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

This is what MDN Web API says about .offsetTop:

offsetTop returns the distance of the current element relative to the top of the offsetParent node

This is what jQuery v.1.11 .offset() basically do when getting the coords:

var box = { top: 0, left: 0 };

// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
  box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
  top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
  left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
  • pageYOffset intuitively says how much was the page scrolled
  • docElem.scrollTop is the fallback for IE<9 (which are BTW unsupported in jQuery 2)
  • docElem.clientTop is the width of the top border of an element (the document in this case)
  • elem.getBoundingClientRect() gets the coords relative to the document viewport (see comments). It may return fraction values, so this is the source of your bug. It also may cause a bug in IE<8 when the page is zoomed. To avoid fraction values, try to calculate the position iteratively

Conclusion

  • If you want coords relative to the parent node, use element.offsetTop. Add element.scrollTop if you want to take the parent scrolling into account. (or use jQuery .position() if you are fan of that library)
  • If you want coords relative to the viewport use element.getBoundingClientRect().top. Add window.pageYOffset if you want to take the document scrolling into account. You don't need to subtract document's clientTop if the document has no border (usually it doesn't), so you have position relative to the document
  • Subtract element.clientTop if you don't consider the element border as the part of the element

SharePoint 2013 get current user using JavaScript

How about this:

$.getJSON(_spPageContextInfo.webServerRelativeUrl + "/_api/web/currentuser")
.done(function(data){ 
    console.log(data.Title);
})
.fail(function() { console.log("Failed")});

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

In my case, I had to setup the public key for another user, as I already had one for my main user. once I switched users and performed the commands in the link above I was able to perform the setup for my test server without a problem.

Differences between Emacs and Vim

Its like apples and oranges. Both have different design and philosphy. Vim is a Text Editor while Emacs is a Lisp Interpreter that does Text Editing.

I use Vim because its fast, sleak, and really good at manipulating texts. It has a composable natural key binding that can make your development tasks really harmonic. Vim is based on the simple *nix philiosphy of doing one thing really well - i.e Text Manipulation.

Extending Vim using bash/zsh and tmux is usually easy and allows you learn a lot of things. IMHO this is a good learning curve. The key thing is to learn how to integrate these things to get a larger working application. With Vim you'll need to learn integration because it doesn't naturally integrate unless you tell it how to. Another worthwhile extension which I use is Tig . Its an ncurses based Git frontend . I just have a binding that opens Tig silently and then I do all the Git stuff there.

Its up to the end user to decide what works best. That Emacs and Vim has stood the test of time is proof of their worthiness. Eventually a good programmer needs nothing more than a pen and a paper to be creative. Good algorithms don't need editors to back them. So try them both and see what makes you more productive. And learn design patterns from both these softwares as there are plenty to learn and discover!

XPath - Difference between node() and text()

For me it was a big difference when I faced this scenario (here my story:)

<?xml version="1.0" encoding="UTF-8"?>
<sentence id="S1.6">When U937 cells were infected with HIV-1, 
        
    <xcope id="X1.6.3">
        <cue ref="X1.6.3" type="negation">no</cue> 
                        
                        induction of NF-KB factor was detected
        
    </xcope>
                    
, whereas high level of progeny virions was produced, 
        
    <xcope id="X1.6.2">
        <cue ref="X1.6.2" type="speculation">suggesting</cue> that this factor was 
        <xcope id="X1.6.1">
            <cue ref="X1.6.1" type="negation">not</cue> required for viral replication
        </xcope>
    </xcope>.

</sentence>

I needed to extract text between tags and aggregate (by concat) the text including in innner tags.

/node() did the job, while /text() made half job

/text() only returned text not included in inner tags, because inner tags are not "text nodes". You may think, "just extract text included in the inner tags in an additional xpath", however, it becomes challenging to sort the text in this original order because you dont know where to place the aggregated text from the inner tags!because you dont know where to place the aggregated text from the inner nodes.

  1. When U937 cells were infected with HIV-1,
  2. no induction of NF-KB factor was detected
  3. , whereas high level of progeny virions was produced,
  4. suggesting that this factor was not required for viral replication
  5. .

Finally, /node() did exactly what I wanted, because it gets the text from inner tags too.

Developing for Android in Eclipse: R.java not regenerating

I had the same issue. When I checked it out I found that the name of the XML resource under layout was not having the correct naming convention. It had some capital letters. So I renamed it to make all letters lowercase and the magic worked.

how to start stop tomcat server using CMD?

Change directory to tomcat/bin directory in cmd prompt

cd C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin

Run the below command to start:

On Linux: >startup.sh

On Windows: >startup.bat

Run these commands to stop

On Linux: shutdown.sh

On Windows: shutdown.bat

How can I get an HTTP response body as a string?

Here's a lightweight way to do so:

String responseString = "";
for (int i = 0; i < response.getEntity().getContentLength(); i++) { 
    responseString +=
    Character.toString((char)response.getEntity().getContent().read()); 
}

With of course responseString containing website's response and response being type of HttpResponse, returned by HttpClient.execute(request)

How to get the current URL within a Django template?

Django 1.9 and above:

## template
{{ request.path }}  #  -without GET parameters 
{{ request.get_full_path }}  # - with GET parameters

Old:

## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

## views.py
from django.template import *

def home(request):
    return render_to_response('home.html', {}, context_instance=RequestContext(request))

## template
{{ request.path }}

Number of days between two dates in Joda-Time

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
                               end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
                               end.toLocalDate()).getDays());
// prints 1

Going via a LocalDate sidesteps the whole issue.

How to load image (and other assets) in Angular an project?

In my project I am using the following syntax in my app.component.html:

<img src="/assets/img/1.jpg" alt="image">

or

<img src='http://mruanova.com/img/1.jpg' alt='image'>

use [src] as a template expression when you are binding a property using interpolation:

<img [src]="imagePath" />

is the same as:

<img src={{imagePath}} />

Source: how to bind img src in angular 2 in ngFor?

How to check if a float value is a whole number

You could use this:

if k == int(k):
    print(str(k) + " is a whole number!")

Send JavaScript variable to PHP variable

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

Passing command line arguments from Maven as properties in pom.xml

You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-

<projectFile>${projectName}</projectFile>

Then on command line you can pass the project name as parameter:-

mvn [your-command] -DprojectName=[name of project]

A failure occurred while executing com.android.build.gradle.internal.tasks

If any one having this issue in flutter after adding firebase storage. Do flutter clean and re run it, it will work

java.net.ConnectException: Connection refused

You probably didn't initialize the server or client is trying to connect to wrong ip/port.

How to do a Jquery Callback after form submit?

$("#formid").ajaxForm({ success: function(){ //to do after submit } });

How to add a list item to an existing unordered list?

Just to add to this thread - if you are moving an existing item you will need to use clone and then true/false on whether you clone/deep-clone the events as well (https://api.jquery.com/clone/).

Example: $("#content ul").append($('.existing_li').clone(true));

jQuery Ajax PUT with parameters

Can you provide an example, because put should work fine as well?

Documentation -

The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url) -

$.ajax({
  url: '/echo/html/',
  type: 'PUT',
  data: "name=John&location=Boston",
  success: function(data) {
    alert('Load was performed.');
  }
});

Demo tested from jQuery 1.3.2 onwards on Chrome.

css to make bootstrap navbar transparent

This works for 4.0.

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
or
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">

key item is fixed-top, otherwise, white or default page background is displayed even if there is a image top. navbar-light gives dark letters, navbar-dark shows light text.

Remove all child elements of a DOM node in JavaScript

elm.replaceChildren()

It's experimental without wide support, but when executed with no params will do what you're asking for, and it's more efficient than looping through each child and removing it. As mentioned already, replacing innerHTML with an empty string will require HTML parsing on the browser's part.

Documentation here.

What are MVP and MVC and what is the difference?

Model-View-Presenter

In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.

MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.

Two primary variations

Passive View: The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.

  • Pro: maximum testability surface; clean separation of the View and Model
  • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.

Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.

  • Pro: by leveraging data binding the amount of code is reduced.
  • Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.

Model-View-Controller

In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:

    Action in the View
        -> Call to Controller
        -> Controller Logic
        -> Controller returns the View.

One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.

Presentation Model

One other pattern to look at is the Presentation Model pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.

There is a MSDN article about the Presentation Model and a section in the Composite Application Guidance for WPF (former Prism) about Separated Presentation Patterns

BeanFactory vs ApplicationContext

In summary:

The ApplicationContext includes all functionality of the BeanFactory. It is generally recommended to use the former.

There are some limited situations such as in a Mobile application, where memory consumption might be critical.

In that scenarios, It can be justifiable to use the more lightweight BeanFactory. However, in the most enterprise applications, the ApplicationContext is what you will want to use.

For more, see my blog post:

Difference between BeanFactory and ApplicationContext in Spring – The java spring blog from the basics

Setting dynamic scope variables in AngularJs - scope.<some_string>

If you are using Lodash library below is the way to set a dynamic variable in the angular scope.

To set the value in the angular scope.

_.set($scope, the_string, 'life.meaning')

To get the value from the angular scope.

_.get($scope, 'life.meaning')

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

I have been using windows for the last 13 years. I found this solution to be truly working for me. I recommend you to follow these steps:

  • let's start by deleting this folder C:\Users\Your-name\AppData\Roaming\syntevo

  • Completely uninstall smart git from the control panel, uninstall programs.

  • Again re-install the smart git and change the default position of installing directory.

  • While configuring smart git, make sure that the non-commercial option is selected that will help you to use the latest as well as a free version for lifetime.

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

Configure webpack (in webpack.config.js) with:

devServer: {
  // ...
  host: '0.0.0.0',
  port: 80,
  // ...
}

Programmatic equivalent of default(Type)

  • In case of a value type use Activator.CreateInstance and it should work fine.
  • When using reference type just return null
public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

What is the newline character in the C language: \r or \n?

'\r' = carriage return and '\n' = line feed.

In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.

SQL Format as of Round off removing decimals

use ROUND () (See examples ) function in sql server

select round(11.6,0)

result:

12.0

ex2:

select round(11.4,0)

result:

11.0

if you don't want the decimal part, you could do

select cast(round(11.6,0) as int)

How to loop through files matching wildcard in batch file

You can use this line to print the contents of your desktop:

FOR %%I in (C:\windows\desktop\*.*) DO echo %%I 

Once you have the %%I variable it's easy to perform a command on it (just replace the word echo with your program)

In addition, substitution of FOR variable references has been enhanced You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only (directory with \)
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

https://ss64.com/nt/syntax-args.html

In the above examples %I and PATH can be replaced by other valid values. The %~ syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.

You can get the full documentation by typing FOR /?

Is try-catch like error handling possible in ASP Classic?

For anytone who has worked in ASP as well as more modern languages, the question will provoke a chuckle. In my experience using a custom error handler (set up in IIS to handle the 500;100 errors) is the best option for ASP error handling. This article describes the approach and even gives you some sample code / database table definition.

http://www.15seconds.com/issue/020821.htm

Here is a link to Archive.org's version

When should you use a class vs a struct in C++?

All class members are private by default and all struct members are public by default. Class has default private bases and Struct has default public bases. Struct in case of C cannot have member functions where as in case of C++ we can have member functions being added to the struct. Other than these differences, I don't find anything surprising about them.

How to display string that contains HTML in twig template?

{{ word|striptags('<b>,<a>,<pre>')|raw }}

if you want to allow multiple tags

MINGW64 "make build" error: "bash: make: command not found"

You have to install mingw-get and after that you can run mingw-get install msys-make to have the command make available.

Here is a link for what you want http://www.mingw.org/wiki/getting_started

Get GPS location from the web browser

There is the GeoLocation API, but browser support is rather thin on the ground at present. Most sites that care about such things use a GeoIP database (with the usual provisos about the inaccuracy of such a system). You could also look at third party services requiring user cooperation such as FireEagle.

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

Retrieve only the queried element in an object array in MongoDB collection

Likewise you can find for the multiple

db.getCollection('localData').aggregate([
    // Get just the docs that contain a shapes element where color is 'red'
  {$match: {'shapes.color': {$in : ['red','yellow'] } }},
  {$project: {
     shapes: {$filter: {
        input: '$shapes',
        as: 'shape',
        cond: {$in: ['$$shape.color', ['red', 'yellow']]}
     }}
  }}
])

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

This error can be caused by the permissions to the file, which you should check, however recently I noticed that the same is thrown if the file has been transferred and windows has marked the file as 'Encrypt Contents to Secure Data'.

You can find this by bringing up the .bak file properties and clicking the advanced button, it appears as the last check box on the dialog.

Hope that helps someone!

How do I order my SQLITE database in descending order, for an android app?

About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html

If you implement this, you will call you data base very efficient.

public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {

   public interface OnLoadEntities {
       void onSuccessLoadEntities(List<Entities> entitiesList);
   }

    private OnLoadEntities onLoadEntities;

    private final Context context;

    private final LoaderManager loaderManager;

    public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
        this.context = context;
        this.loaderManager = loaderManager;
    }

    public void setCallback(OnLoadEntities onLoadEntities) {
        this.onLoadEntities = onLoadEntities;
    }

    public void loadEntities() {
        loaderManager.initLoader(LOADER_ID, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

How might I find the largest number contained in a JavaScript array?

Finding max and min value the easy and manual way. This code is much faster than Math.max.apply; I have tried up to 1000k numbers in array.

function findmax(array)
{
    var max = 0;
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] > max)
        {
            max = array[counter];
        }
    }
    return max;
}

function findmin(array)
{
    var min = array[0];
    var a = array.length;
    for (counter=0;counter<a;counter++)
    {
        if (array[counter] < min)
        {
            min = array[counter];
        }
    }
    return min;
}

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

change below line of code

spring.datasource.driverClassName

to

spring.datasource.driver-class-name

draw diagonal lines in div background with CSS

If you'd like the cross to be partially transparent, the naive approach would be to make linear-gradient colors semi-transparent. But that doesn't work out good due to the alpha blending at the intersection, producing a differently colored diamond. The solution to this is to leave the colors solid but add transparency to the gradient container instead:

_x000D_
_x000D_
.cross {_x000D_
  position: relative;_x000D_
}_x000D_
.cross::after {_x000D_
  pointer-events: none;_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0; bottom: 0; left: 0; right: 0;_x000D_
}_x000D_
_x000D_
.cross1::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%);_x000D_
}_x000D_
_x000D_
.cross2::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%);_x000D_
  opacity: 0.35;_x000D_
}_x000D_
_x000D_
div { width: 180px; text-align: justify; display: inline-block; margin: 20px; }
_x000D_
<div class="cross cross1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>_x000D_
_x000D_
<div class="cross cross2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>
_x000D_
_x000D_
_x000D_

Appending an element to the end of a list in Scala

This is similar to one of the answers but in different way :

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

Python: Converting from ISO-8859-1/latin1 to UTF-8

Decode to Unicode, encode the results to UTF8.

apple.decode('latin1').encode('utf8')

.trim() in JavaScript not working in IE

jQuery:

$.trim( $("#mycomment").val() );

Someone uses $("#mycomment").val().trim(); but this will not work on IE.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.

Decrementing for loops

Check out the range documentation, you have to define a negative step:

>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Android studio takes too much memory

In my case, there were two main sources of memory hogging: the IDE and Gradle:

Android Studio (up to 1.5GB)

The IDE's JVM is configured to have a max heap size. You can see this in the lower-right corner of the main interface:

Android Studio showing 725M max heap size

You can reduce this by editing the memory-related settings in the .vmoptions file. For example, I changed my max heap size to 512MB:

-Xmx512m

Unfortunately, I found that lowering this value increases the frequency of Android Studio temporarily freezing, perhaps to do its garbage collection.

Gradle (up to 1.5GB)

Gradle can also use a lot of RAM after developing for a while. Windows just shows it as Java(TM) Platform SE Binary:

Windows 8.1 Task Manager showing "Java(TM Platform SE binary" using 1,460.5 MB of memory

You can fix this by changing the Gradle JVM options. You can do this on a per-user basis by editing gradle.properties:

  1. Open the gradle.properties file, creating it if it doesn't exist:
    • Windows: %USERPROFILE%\.gradle\gradle.properties
    • Linux/Mac: ~/.gradle/gradle.properties
  2. Update the org.gradle.jvmargs property, creating it if necessary. I set mine to this:

    org.gradle.jvmargs=-Xmx256m -XX:MaxPermSize=256m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
    

I haven't noticed any difference in build performance for my small project with the max heap size set to 256MB (-Xmx256m).

Note that you might need to restart Android Studio so the old Gradle process is killed; otherwise you might end up with both running at the same time.

Emulator

Regarding the emulator taking up a lot of your RAM, your screenshot shows it taking about 800MB. You can choose how much RAM to allocate to the emulator:

  1. Edit the AVD
  2. Press Show Advanced Settings
  3. Reduce the value of RAM

Android Virtual Device RAM configuration

Draw Circle using css alone

You could use a .before with a content with a unicode symbol for a circle (25CF).

_x000D_
_x000D_
.circle:before {_x000D_
  content: ' \25CF';_x000D_
  font-size: 200px;_x000D_
}
_x000D_
<span class="circle"></span>
_x000D_
_x000D_
_x000D_

I suggest this as border-radius won't work in IE8 and below (I recognize the fact that the suggestion is a bit mental).

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

I find db.serverCmdLineOpts() the most robust way to find actual path if you can connect to the server. The "parsed.storage.dbPath" contains the path your server is currently using and is available both when it's taken from the config or from the command line arguments.

Also in my case it was important to make sure that the config value reflects the actual value (i.e. config didn't change after the last restart), which isn't guaranteed by the solutions offered here.

db.serverCmdLineOpts()

Example output:

{
    "argv" : [ 
        // --
    ],
    "parsed" : {
        "config" : "/your-config",
        "storage" : {
            "dbPath" : "/your/actual/db/path",
            // --
        }
    },
    "ok" : 1.0
}

How does the "final" keyword in Java work? (I can still modify an object.)

I thought of writing an updated and in depth answer here.

final keyword can be used in several places.

  1. classes

A final class means that no other class can extend that final class. When Java Run Time (JRE) knows an object reference is in type of a final class (say F), it knows that the value of that reference can only be in type of F.

Ex:

F myF;
myF = new F();    //ok
myF = someOther;  //someOther cannot be in type of a child class of F.
                  //because F cannot be extended.

So when it executes any method of that object, that method doesn't need to be resolved at run time using a virtual table. i.e. run-time polymorphism cannot be applied. So the run time doesn't bother about that. Which means it saves processing time, which will improve performance.

  1. methods

A final method of any class means that any child class extending that class cannot override that final method(s). So the run time behavior in this scenario is also quite same with the previous behavior I mentioned for classes.

  1. fields, local variables, method parameters

If one specified any kind of above as final, it means that the value is already finalized, so the value cannot be changed.

Ex:

For fields, local parameters

final FinalClass fc = someFC; //need to assign straight away. otherwise compile error.
final FinalClass fc; //compile error, need assignment (initialization inside a constructor Ok, constructor can be called only once)
final FinalClass fc = new FinalClass(); //ok
fc = someOtherFC; //compile error
fc.someMethod(); //no problem
someOtherFC.someMethod(); //no problem

For method parameters

void someMethod(final String s){
    s = someOtherString; //compile error
}

This simply means that value of the final reference value cannot be changed. i.e. only one initialization is allowed. In this scenario, in run time, since JRE knows that values cannot be changed, it loads all these finalized values (of final references) into L1 cache. Because it doesn't need to load back again and again from main memory. Otherwise it loads to L2 cache and does time to time loading from main memory. So it is also a performance improvement.

So in all above 3 scenarios, when we have not specified the final keyword in places we can use, we don't need to worry, compiler optimizations will do that for us. There are also lots of other things that compiler optimizations do for us. :)

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

This error was occurring for me in Firefox but not Chrome while developing locally, and it turned out to be caused by Firefox not trusting my local API's ssl certificate (which is not valid, but I had added it to my local cert store, which let chrome trust it but not ff). Navigating to the API directly and adding an exception in Firefox fixed the issue.

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

How to convert password into md5 in jquery?

Fiddle: http://jsfiddle.net/33HMj/

Js:

var md5 = function(value) {
    return CryptoJS.MD5(value).toString();
}

$("input").keyup(function () {
     var value = $(this).val(),
         hash = md5(value);
     $(".test").html(hash);
 });

Running PowerShell as another user, and launching a script

In windows server 2012 or 2016 you can search for Windows PowerShell and then "Pin to Start". After this you will see "Run as different user" option on a right click on the start page tiles.

How can I show an element that has display: none in a CSS rule?

document.getElementById('mybox').style.display = "block";

Viewing localhost website from mobile device

You can solve the problem by downloading the 'conveyor' library from extensions and update in Visual Studio.

You can access it from other devices.

  • Open Visual Studio

  • Tools > Extensions and Updates

  • Online > Visual Studio Marketplace

  • Search 'Conveyor'
  • Download and install this extension

When you launch the API, you can access it from other devices. This plugin creates a link from your own ip address.

Example: https://youripadress:5000/api/values

Adding a splash screen to Flutter apps

persons who are getting the error like image not found after applying the verified answer make sure that you are adding @mipmap/ic_launcher instead of @mipmap/ ic_launcher.png

UPDATE and REPLACE part of a string

you should use the below update query

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id IN(1, 2, 3, 4)

UPDATE dbo.xxx SET Value=REPLACE(Value,'123\','') WHERE Id <= 4

Either of the above queries should work.

how to display a javascript var in html body

You cannot add JavaScript variable to HTML code.

For this you need to do in following way.

<html>
<head>
<script type="text/javscript">
var number = 123;

document.addEventListener('DOMContentLoaded', function() {
   document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>

Angular 2 router no base href set

With angular 4 you can fix this issue by updating app.module.ts file as follows:

Add import statement at the top as below:

import {APP_BASE_HREF} from '@angular/common';

And add below line inside @NgModule

providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]

Reff: https://angular.io/api/common/APP_BASE_HREF

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

The download from java.com which installs in /Library/Internet Plug-Ins is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home which you can then add to Eclipse via Preferences -> Java -> Installed JREs.

How to increment a JavaScript variable using a button press event

yes, supposing your variable is in the global namespace:

<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>

How to read a file in reverse order?

with open("filename") as f:

    print(f.read()[::-1])

How to convert an Instant to a date format?

An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).

To print it as a date/time, you first need to decide which timezone to use. For example:

System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));

This will print the date/time in iso format: 2015-06-02T10:15:02.325

If you want a different format you can use a formatter:

LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);

C# Version Of SQL LIKE

Operators.LikeString

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators.likestring(v=vs.100).ASPX

public static bool LikeString(
    string Source,
    string Pattern,
    CompareMethod CompareOption
)

Split comma-separated values

Split a Textbox value separated by comma and count the total number of values in text and splitted values are shown in ritchTextBox.

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "";
        richTextBox1.Text = "";

        string strText = textBox1.Text.Trim();
        string[] strArr = strText.Split(',');
        int count = 0;
        for (int i = 0; i < strArr.Length; i++)
        {
            count++;
        }
        label1.Text = Convert.ToString(count);
        for (int i = 0; i < strArr.Length; i++)
        {
            richTextBox1.Text += strArr[i].Trim() + "\n";
        }
    }

How to grep, excluding some patterns?

A bit old, but oh well...

The most up-voted solution from @houbysoft will not work as that will exclude any line with "gloom" in it, even if it has "loom". According to OP's expectations, we need to include lines with "loom", even if they also have "gloom" in them. This line needs to be in the output "Arty is slooming in a gloomy day.", but this will be excluded by a chained grep like

grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'

Instead, the egrep regex example of Bentoy13 works better

egrep '(^|[^g])loom' ~/projects/**/trunk/src/**/*.@(h|cpp)

as it will include any line with "loom" in it, regardless of whether or not it has "gloom". On the other hand, if it only has gloom, it will not include it, which is precisely the behaviour OP wants.

How can I get javascript to read from a .json file?

NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA

If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):

_x000D_
_x000D_
var xmlhttp = new XMLHttpRequest();_x000D_
xmlhttp.onreadystatechange = function() {_x000D_
    if (this.readyState == 4 && this.status == 200) {_x000D_
        var myObj = JSON.parse(this.responseText);_x000D_
        document.getElementById("demo").innerHTML = myObj.name;_x000D_
    }_x000D_
};_x000D_
xmlhttp.open("GET", "json_demo.txt", true);_x000D_
xmlhttp.send();
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<h2>Use the XMLHttpRequest to get the content of a file.</h2>_x000D_
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Here's a summary:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Here's the example used:

_x000D_
_x000D_
var json = '{"result":true, "count":42}';_x000D_
obj = JSON.parse(json);_x000D_
_x000D_
console.log(obj.count);_x000D_
// expected output: 42_x000D_
_x000D_
console.log(obj.result);_x000D_
// expected output: true
_x000D_
_x000D_
_x000D_

Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/

Since it isn't working, I'd try using XMLHttpRequests

You could also try AJAX requests:

$.ajax({
    'async': false,
    'global': false,
    'url': "/jsonfile.json",
    'dataType': "json",
    'success': function (data) {
        // do stuff with data
    }
});

Documentation: http://api.jquery.com/jquery.ajax/

How to do paging in AngularJS?

This is a pure javascript solution that I've wrapped as an Angular service to implement pagination logic like in google search results.

Working demo on CodePen at http://codepen.io/cornflourblue/pen/KVeaQL/

Details and explanation at this blog post

function PagerService() {
    // service definition
    var service = {};

    service.GetPager = GetPager;

    return service;

    // service implementation
    function GetPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;

        // default page size is 10
        pageSize = pageSize || 10;

        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);

        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }

        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = startIndex + pageSize;

        // create an array of pages to ng-repeat in the pager control
        var pages = _.range(startPage, endPage + 1);

        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }
}

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use directions service of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map.

Information and examples about rendering the directions route on the map can be found in rendering directions section of Google Maps API v3 documentation.

"End of script output before headers" error in Apache

Since no answer is accepted, I would like to provide one possible solution. If your script is written on Windows and uploaded to a Linux server(through FTP), then the problem will raise usually. The reason is that Windows uses CRLF to end each line while Linux uses LF. So you should convert it from CRLF to LF with the help of an editor, such Atom, as following enter image description here

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I got a similar error message like TCP error code 10061: No connection could be made because the target machine actively refused it in my current project. I find this 10061 error code cannot distinguish the case that the service endpoint is not started and the case that it is blocked by the firewall. Often, the firewall can be switched off, but the problem is still there.

You can test your code in the below two ways.

  1. Insert code to get time A that service is started and time B that client sends the request to the server. If B is earlier than A, it can cause this problem.
  2. Change your server port to another port that is also available in the system. You will find the same error code reported.

Above is my fix. It works on my machine. I hope it helps!

Asp Net Web API 2.1 get client IP address

My solution is similar to user1587439's answer, but works directly on the controller's instance (instead of accessing HttpContext.Current).

In the 'Watch' window, I saw that this.RequestContext.WebRequest contains the 'UserHostAddress' property, but since it relies on the WebHostHttpRequestContext type (which is internal to the 'System.Web.Http' assembly) - I wasn't able to access it directly, so I used reflection to directly access it:

string hostAddress = ((System.Web.HttpRequestWrapper)this.RequestContext.GetType().Assembly.GetType("System.Web.Http.WebHost.WebHostHttpRequestContext").GetProperty("WebRequest").GetMethod.Invoke(this.RequestContext, null)).UserHostAddress;

I'm not saying it's the best solution. using reflection may cause issues in the future in case of framework upgrade (due to name changes), but for my needs it's perfect

Android Material Design Button Styles

I will add my answer since I don't use any of the other answers provided.

With the Support Library v7, all the styles are actually already defined and ready to use, for the standard buttons, all of these styles are available:

style="@style/Widget.AppCompat.Button"
style="@style/Widget.AppCompat.Button.Colored"
style="@style/Widget.AppCompat.Button.Borderless"
style="@style/Widget.AppCompat.Button.Borderless.Colored"

Widget.AppCompat.Button: enter image description here

Widget.AppCompat.Button.Colored: enter image description here

Widget.AppCompat.Button.Borderless enter image description here

Widget.AppCompat.Button.Borderless.Colored: enter image description here


To answer the question, the style to use is therefore

<Button style="@style/Widget.AppCompat.Button.Colored"
.......
.......
.......
android:text="Button"/>

How to change the color

For the whole app:

The color of all the UI controls (not only buttons, but also floating action buttons, checkboxes etc.) is managed by the attribute colorAccent as explained here. You can modify this style and apply your own color in your theme definition:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="colorAccent">@color/Orange</item>
</style>

For a specific button:

If you need to change the style of a specific button, you can define a new style, inheriting one of the parent styles described above. In the example below I just changed the background and font colors:

<style name="AppTheme.Button" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/Red</item>
    <item name="android:textColor">@color/White</item>
</style>

Then you just need to apply this new style on the button with:

android:theme="@style/AppTheme.Button"

To set a default button design in a layout, add this line to the styles.xml theme:

<item name="buttonStyle">@style/btn</item>

where @style/btn is your button theme. This sets the button style for all the buttons in a layout with a specific theme

Cannot add or update a child row: a foreign key constraint fails

It means that you're trying to insert into table2 a UserID value that doesn't exist in table1.

Upload files from Java client to a HTTP server

click link get example file upload clint java with apache HttpComponents

http://hc.apache.org/httpcomponents-client-ga/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

and library downalod link

https://hc.apache.org/downloads.cgi

use 4.5.3.zip it's working fine in my code

and my working code..

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ClientMultipartFormPost {

     public static void main(String[] args) throws Exception {

          CloseableHttpClient httpclient = HttpClients.createDefault();
          try {
             HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");

             FileBody bin = new FileBody(new File("E:\\meter.jpg"));
             StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

             HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("bin", bin)
                .addPart("comment", comment)
                .build();


             httppost.setEntity(reqEntity);

             System.out.println("executing request " + httppost.getRequestLine());
             CloseableHttpResponse response = httpclient.execute(httppost);
           try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                     System.out.println("Response content length: " +    resEntity.getContentLength());
                }
              EntityUtils.consume(resEntity);
             } finally {
                 response.close();
            }
       } finally {
          httpclient.close();
      }
   }

}

How to check if a String contains any letter from a to z?

Replace your for loop by this :

errorCounter = Regex.Matches(yourstring,@"[a-zA-Z]").Count;

Remember to use Regex class, you have to using System.Text.RegularExpressions; in your import

Pandas: Setting no. of max rows

Set display.max_rows:

pd.set_option('display.max_rows', 500)

For older versions of pandas (<=0.11.0) you need to change both display.height and display.max_rows.

pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)

See also pd.describe_option('display').

You can set an option only temporarily for this one time like this:

from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
    display(df) #need display to show the dataframe when using with in jupyter
    #some pandas stuff

You can also reset an option back to its default value like this:

pd.reset_option('display.max_rows')

And reset all of them back:

pd.reset_option('all')

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

Maybe VT-X is not enabled in your BIOS.

See Intel HAXM documentation here: http://software.intel.com/en-us/articles/installation-instructions-for-intel-hardware-accelerated-execution-manager-windows

Intel VT-x not enabled

In some cases, Intel VT-x may be disabled in the system BIOS and must be enabled within the BIOS setup utility. To access the BIOS setup utility, a key must be pressed during the computer’s boot sequence. This key is dependent on which BIOS is used but it is typically the F2, Delete, or Esc key. Within the BIOS setup utility, Intel VT may be identified by the terms "VT", "Virtualization Technology", or "VT-d." Make sure to enable all of the Virtualization features.

Multiple WHERE clause in Linq

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" &&
                  r.Field<string>("UserName") != "YYYY"
            select r;

DataTable newDT = query.CopyToDataTable();

Note the && instead of ||. You want to select the row if the username isn't XXXX and the username isn't YYYY.

EDIT: If you have a whole collection, it's even easier. Suppose the collection is called ignoredUserNames:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where !ignoredUserNames.Contains(r.Field<string>("UserName"))
            select r;

DataTable newDT = query.CopyToDataTable();

Ideally you'd want to make this a HashSet<string> to avoid the Contains call taking a long time, but if the collection is small enough it won't make much odds.

How to select unique records by SQL

There are 4 methods you can use:

  1. DISTINCT
  2. GROUP BY
  3. Subquery
  4. Common Table Expression (CTE) with ROW_NUMBER()

Consider the following sample TABLE with test data:

/** Create test table */
CREATE TEMPORARY TABLE dupes(word text, num int, id int);

/** Add test data with duplicates */
INSERT INTO dupes(word, num, id)
VALUES ('aaa', 100, 1)
      ,('bbb', 200, 2)
      ,('ccc', 300, 3)
      ,('bbb', 400, 4)
      ,('bbb', 200, 5)     -- duplicate
      ,('ccc', 300, 6)     -- duplicate
      ,('ddd', 400, 7)
      ,('bbb', 400, 8)     -- duplicate
      ,('aaa', 100, 9)     -- duplicate
      ,('ccc', 300, 10);   -- duplicate

Option 1: SELECT DISTINCT

This is the most simple and straight forward, but also the most limited way:

SELECT DISTINCT word, num 
FROM    dupes
ORDER BY word, num;

/*
word|num|
----|---|
aaa |100|
bbb |200|
bbb |400|
ccc |300|
ddd |400|
*/

Option 2: GROUP BY

Grouping allows you to add aggregated data, like the min(id), max(id), count(*), etc:

SELECT  word, num, min(id), max(id), count(*)
FROM    dupes
GROUP BY word, num
ORDER BY word, num;

/*
word|num|min|max|count|
----|---|---|---|-----|
aaa |100|  1|  9|    2|
bbb |200|  2|  5|    2|
bbb |400|  4|  8|    2|
ccc |300|  3| 10|    3|
ddd |400|  7|  7|    1|
*/

Option 3: Subquery

Using a subquery, you can first identify the duplicate rows to ignore, and then filter them out in the outer query with the WHERE NOT IN (subquery) construct:

/** Find the higher id values of duplicates, distinct only added for clarity */
    SELECT  distinct d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id

/*
id|
--|
 5|
 6|
 8|
 9|
10|
*/

/** Use the previous query in a subquery to exclude the dupliates with higher id values */
SELECT  *
FROM    dupes
WHERE   id NOT IN (
    SELECT  d2.id
    FROM    dupes d1
        INNER JOIN dupes d2 ON d2.word=d1.word AND d2.num=d1.num
    WHERE d2.id > d1.id
)
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/

Option 4: Common Table Expression with ROW_NUMBER()

In the Common Table Expression (CTE), select the ROW_NUMBER(), partitioned by the group column and ordered in the desired order. Then SELECT only the records that have ROW_NUMBER() = 1:

WITH CTE AS (
    SELECT  *
           ,row_number() OVER(PARTITION BY word, num ORDER BY id) AS row_num
    FROM    dupes
)
SELECT  word, num, id 
FROM    cte
WHERE   row_num = 1
ORDER BY word, num;

/*
word|num|id|
----|---|--|
aaa |100| 1|
bbb |200| 2|
bbb |400| 4|
ccc |300| 3|
ddd |400| 7|
*/

Device not detected in Eclipse when connected with USB cable

I had similar problem, drivers was okey, but Eclipse did show me the device in Run > Run Configurations > Target tab. But I checked the option "Always prompt to pick device". And then running the application from Eclipse the prompt window finally showed my device.

What is the difference between String.slice and String.substring?

Note: if you're in a hurry, and/or looking for short answer scroll to the bottom of the answer, and read the last two lines.if Not in a hurry read the whole thing.


let me start by stating the facts:

Syntax:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
Note #1: slice()==substring()

What it does?
The slice() method extracts parts of a string and returns the extracted parts in a new string.
The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
The substring() method extracts parts of a string and returns the extracted parts in a new string.
Note #2:slice()==substring()

Changes the Original String?
slice() Doesn't
substr() Doesn't
substring() Doesn't
Note #3:slice()==substring()

Using Negative Numbers as an Argument:
slice() selects characters starting from the end of the string
substr()selects characters starting from the end of the string
substring() Doesn't Perform
Note #3:slice()==substr()

if the First Argument is Greater than the Second:
slice() Doesn't Perform
substr() since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring() will swap the two arguments, and perform as usual

the First Argument:
slice() Required, indicates: Starting Index
substr() Required, indicates: Starting Index
substring() Required, indicates: Starting Index
Note #4:slice()==substr()==substring()

the Second Argument:
slice() Optional, The position (up to, but not including) where to end the extraction
substr() Optional, The number of characters to extract
substring() Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()

What if the Second Argument is Omitted?
slice() selects all characters from the start-position to the end of the string
substr() selects all characters from the start-position to the end of the string
substring() selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()

so, you can say that there's a difference between slice() and substr(), while substring() is basically a copy of slice().

in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr().

convert HTML ( having Javascript ) to PDF using JavaScript

I'm surprised no one mentioned the possibility to use an API to do the work.

Granted, if you want to stay secure, converting HTML to PDF directly from within the browser using javascript is not a good idea.

But here's what you can do:

When your user hit the "Print" (for example) button, you:

  1. Send a request to your server at a specific endpoint with details about what to convert (URL of the page for instance).
  2. This endpoint will then send the data to convert to an API, and will receive the PDF in response
  3. which it will return to your user.

For a user point of view, they will receive a PDF by clicking on a button.

There are many available API that does the job, some better than others (that's not why I'm here) and a Google search will give you a lot of answers.

Depending on what is written your backend, you might be interested in PDFShift (Truth: I work there).

They offer ready to work packages for PHP, Python and Node.js. All you have to do is install the package, create an account, indicate your API key and you are all set!

The advantage of the API is that they work well in all languages. All you have to do is a request (generally POST) containing the data you want to be converted and get a PDF back. And depending on your usage, it's generally free, except if you are a heavy user.