Programs & Examples On #Ejb 2.x

This tag is used for question related to the session bean and message-driven bean component types of the EJB 2.x programming model. For questions about the persistent entities defined in the document "Java Persistence API" of the EJB 2.x specification, use the [JPA] tag.

Get Android Device Name

On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL could be "SM-G920F", "SM-G920I", or "SM-G920W8".

I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:

AndroidDeviceNames Library on Github


If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:

/** Returns the consumer friendly device name */
public static String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(manufacturer)) {
        return capitalize(model);
    }
    return capitalize(manufacturer) + " " + model;
}

private static String capitalize(String str) {
    if (TextUtils.isEmpty(str)) {
        return str;
    }
    char[] arr = str.toCharArray();
    boolean capitalizeNext = true;
    String phrase = "";
    for (char c : arr) {
        if (capitalizeNext && Character.isLetter(c)) {
            phrase += Character.toUpperCase(c);
            capitalizeNext = false;
            continue;
        } else if (Character.isWhitespace(c)) {
            capitalizeNext = true;
        }
        phrase += c;
    }
    return phrase;
}

Example from my Verizon HTC One M8:

// using method from above
System.out.println(getDeviceName());
// Using https://github.com/jaredrummler/AndroidDeviceNames
System.out.println(DeviceName.getDeviceName());

Result:

HTC6525LVW

HTC One (M8)

Pass Method as Parameter using C#

You need to use a delegate. In this case all your methods take a string parameter and return an int - this is most simply represented by the Func<string, int> delegate1. So your code can become correct with as simple a change as this:

public bool RunTheMethod(Func<string, int> myMethodName)
{
    // ... do stuff
    int i = myMethodName("My String");
    // ... do more stuff
    return true;
}

Delegates have a lot more power than this, admittedly. For example, with C# you can create a delegate from a lambda expression, so you could invoke your method this way:

RunTheMethod(x => x.Length);

That will create an anonymous function like this:

// The <> in the name make it "unspeakable" - you can't refer to this method directly
// in your own code.
private static int <>_HiddenMethod_<>(string x)
{
    return x.Length;
}

and then pass that delegate to the RunTheMethod method.

You can use delegates for event subscriptions, asynchronous execution, callbacks - all kinds of things. It's well worth reading up on them, particularly if you want to use LINQ. I have an article which is mostly about the differences between delegates and events, but you may find it useful anyway.


1 This is just based on the generic Func<T, TResult> delegate type in the framework; you could easily declare your own:

public delegate int MyDelegateType(string value)

and then make the parameter be of type MyDelegateType instead.

“tag already exists in the remote" error after recreating the git tag

If you want to UPDATE a tag, let's say it 1.0.0

  1. git checkout 1.0.0
  2. make your changes
  3. git ci -am 'modify some content'
  4. git tag -f 1.0.0
  5. delete remote tag on github: git push origin --delete 1.0.0
  6. git push origin 1.0.0

DONE

How do you hide the Address bar in Google Chrome for Chrome Apps?

For Chrome on Ubuntu (16.04), F11 is the way to go.

How to set a Postgresql default value datestamp like 'YYYYMM'?

Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.

But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like

SELECT  [columns] FROM table WHERE yearmonth = '200801'

instead of

SELECT  [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')

function is not defined error in Python

It would help if you showed the code you are using for the simple test program. Put directly into the interpreter this seems to work.

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1, 2)
3
>>> 

How do I create a new user in a SQL Azure database?

I think the templates use the following notation: variable name, variable type, default value.

Sysname is a built-in data type which can hold the names of system objects.

It is limited to 128 Unicode character.

-- same as sysname type
declare @my_sysname nvarchar(128);

Find the min/max element of an array in JavaScript

You can use lodash's methods

_.max([4, 2, 8, 6]);
returns => 8

https://lodash.com/docs/4.17.15#max

_.min([4, 2, 8, 6]);
returns => 2

https://lodash.com/docs/4.17.15#min

How to sort an array in descending order in Ruby

For those folks who like to measure speed in IPS ;)

require 'benchmark/ips'

ary = []
1000.times { 
  ary << {:bar => rand(1000)} 
}

Benchmark.ips do |x|
  x.report("sort")               { ary.sort{ |a,b| b[:bar] <=> a[:bar] } }
  x.report("sort reverse")       { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse }
  x.report("sort_by -a[:bar]")   { ary.sort_by{ |a| -a[:bar] } }
  x.report("sort_by a[:bar]*-1") { ary.sort_by{ |a| a[:bar]*-1 } }
  x.report("sort_by.reverse!")   { ary.sort_by{ |a| a[:bar] }.reverse }
  x.compare!
end

And results:

Warming up --------------------------------------
                sort    93.000  i/100ms
        sort reverse    91.000  i/100ms
    sort_by -a[:bar]   382.000  i/100ms
  sort_by a[:bar]*-1   398.000  i/100ms
    sort_by.reverse!   397.000  i/100ms
Calculating -------------------------------------
                sort    938.530  (± 1.8%) i/s -      4.743k in   5.055290s
        sort reverse    901.157  (± 6.1%) i/s -      4.550k in   5.075351s
    sort_by -a[:bar]      3.814k (± 4.4%) i/s -     19.100k in   5.019260s
  sort_by a[:bar]*-1      3.732k (± 4.3%) i/s -     18.706k in   5.021720s
    sort_by.reverse!      3.928k (± 3.6%) i/s -     19.850k in   5.060202s

Comparison:
    sort_by.reverse!:     3927.8 i/s
    sort_by -a[:bar]:     3813.9 i/s - same-ish: difference falls within error
  sort_by a[:bar]*-1:     3732.3 i/s - same-ish: difference falls within error
                sort:      938.5 i/s - 4.19x  slower
        sort reverse:      901.2 i/s - 4.36x  slower

How can I get nth element from a list?

Look here, the operator used is !!.

I.e. [1,2,3]!!1 gives you 2, since lists are 0-indexed.

What is output buffering?

UPDATE 2019. If you have dedicated server and SSD or better NVM, 3.5GHZ. You shouldn't use buffering to make faster loaded website in 100ms-150ms.

Becouse network is slowly than proccesing script in the 2019 with performance servers (severs,memory,disk) and with turn on APC PHP :) To generated script sometimes need only 70ms another time is only network takes time, from 10ms up to 150ms from located user-server.

so if you want be fast 150ms, buffering make slowl, becouse need extra collection buffer data it make extra cost. 10 years ago when server make 1s script, it was usefull.

Please becareful output_buffering have limit if you would like using jpg to loading it can flush automate and crash sending.

Cheers.

You can make fast river or You can make safely tama :)

Check if page gets reloaded or refreshed in JavaScript

First step is to check sessionStorage for some pre-defined value and if it exists alert user:

if (sessionStorage.getItem("is_reloaded")) alert('Reloaded!');

Second step is to set sessionStorage to some value (for example true):

sessionStorage.setItem("is_reloaded", true);

Session values kept until page is closed so it will work only if page reloaded in a new tab with the site. You can also keep reload count the same way.

How can I get a file's size in C++?

If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.

python's re: return True if string contains regex pattern

You can do something like this:

Using search will return a SRE_match object, if it matches your search string.

>>> import re
>>> m = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

If not, it will return None

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    n.group()
AttributeError: 'NoneType' object has no attribute 'group'

And just to print it to demonstrate again:

>>> print n
None

How to run only one task in ansible playbook?

I would love the ability to use a role as a collection of tasks such that, in my playbook, I can choose which subset of tasks to run. Unfortunately, the playbook can only load them all in and then you have to use the --tags option on the cmdline to choose which tasks to run. The problem with this is that all of the tasks will run unless you remember to set --tags or --skip-tags.

I have set up some tasks, however, with a when: clause that will only fire if a var is set.

e.g.

# role/stuff/tasks/main.yml
- name: do stuff
  when: stuff|default(false)

Now, this task will not fire by default, but only if I set the stuff=true

$ ansible-playbook -e '{"stuff":true}'

or in a playbook:

roles:
- {"role":"stuff", "stuff":true}

What's the -practical- difference between a Bare and non-Bare repository?

5 years too late, I know, but no-one actually answered the question:

Then, why should I use the bare repository and why not? What's the practical difference? That would not be beneficial to more people working on a project, I suppose.

What are your methods for this kind of work? Suggestions?

To quote directly from the Loeliger/MCullough book (978-1-449-31638-9, p196/7):

A bare repository might seem to be of little use, but its role is crucial: to serve as an authoritative focal point for collaborative development. Other developers clone and fetch from the bare repository and push updates to it... if you set up a repository into which developers push changes, it should be bare. In effect, this is a special case of the more general best practice that a published repository should be bare.

What is a semaphore?

I've created the visualization which should help to understand the idea. Semaphore controls access to a common resource in a multithreading environment. enter image description here

ExecutorService executor = Executors.newFixedThreadPool(7);

Semaphore semaphore = new Semaphore(4);

Runnable longRunningTask = () -> {
    boolean permit = false;
    try {
        permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
        if (permit) {
            System.out.println("Semaphore acquired");
            Thread.sleep(5);
        } else {
            System.out.println("Could not acquire semaphore");
        }
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    } finally {
        if (permit) {
            semaphore.release();
        }
    }
};

// execute tasks
for (int j = 0; j < 10; j++) {
    executor.submit(longRunningTask);
}
executor.shutdown();

Output

Semaphore acquired
Semaphore acquired
Semaphore acquired
Semaphore acquired
Could not acquire semaphore
Could not acquire semaphore
Could not acquire semaphore

Sample code from the article

How to customize the background/border colors of a grouped table view cell?

One thing I ran into with the above CustomCellBackgroundView code from Mike Akers which might be useful to others:

cell.backgroundView doesn't get automatically redrawn when cells are reused, and changes to the backgroundView's position var don't affect reused cells. That means long tables will have incorrectly drawn cell.backgroundViews given their positions.

To fix this without having to create a new backgroundView every time a row is displayed, call [cell.backgroundView setNeedsDisplay] at the end of your -[UITableViewController tableView:cellForRowAtIndexPath:]. Or for a more reusable solution, override CustomCellBackgroundView's position setter to include a [self setNeedsDisplay].

Print Combining Strings and Numbers

In Python 3.6

a, b=1, 2 

print ("Value of variable a is: ", a, "and Value of variable b is :", b)

print(f"Value of a is: {a}")

How do I list all files of a directory?

If you are looking for a Python implementation of find, this is a recipe I use rather frequently:

from findtools.find_files import (find_files, Match)

# Recursively find all *.sh files in **/usr/bin**
sh_files_pattern = Match(filetype='f', name='*.sh')
found_files = find_files(path='/usr/bin', match=sh_files_pattern)

for found_file in found_files:
    print found_file

So I made a PyPI package out of it and there is also a GitHub repository. I hope that someone finds it potentially useful for this code.

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

How to get the parent dir location

A simple way can be:

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

Make button width fit to the text

Keeping the element's size relative to its content can also be done with display: inline-flex and display: table

The centering can be done with..

  • text-align: center; on the parent (or above, it's inherited)

  • display: flex; and justify-content: center; on the parent

  • position: absolute; left: 50%; transform: translateX(-50%); on the element with position: relative; (at least) on the parent.

Here's a flexbox guide from CSS Tricks

Here's an article on centering from CSS Tricks.

Keeping an element only as wide as its content..

  • Can use display: table;

  • Or inline-anything including inline-flex as used in my snippet example below.

Keep in mind that when centering with flexbox's justify-content: center; when the text wraps the text will align left. So you will still need text-align: center; if your site is responsive and you expect lines to wrap.

_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  padding: 20px;_x000D_
}_x000D_
.container {_x000D_
  display: flex;_x000D_
  justify-content: center; /* center horizontally */_x000D_
  align-items: center; /* center vertically */_x000D_
  height: 50%;_x000D_
}_x000D_
.container.c1 {_x000D_
  text-align: center; /* needed if the text wraps */_x000D_
  /* text-align is inherited, it can be put on the parent or the target element */_x000D_
}_x000D_
.container.c2 {_x000D_
 /* without text-align: center; */_x000D_
}_x000D_
.button {_x000D_
  padding: 5px 10px;_x000D_
  font-size: 30px;_x000D_
  text-decoration: none;_x000D_
  color: hsla(0, 0%, 90%, 1);_x000D_
  background: linear-gradient(hsla(21, 85%, 51%, 1), hsla(21, 85%, 61%, 1));_x000D_
  border-radius: 10px;_x000D_
  box-shadow: 2px 2px 15px -5px hsla(0, 0%, 0%, 1);_x000D_
}_x000D_
.button:hover {_x000D_
  background: linear-gradient(hsl(207.5, 84.8%, 51%), hsla(207, 84%, 62%, 1));_x000D_
  transition: all 0.2s linear;_x000D_
}_x000D_
.button.b1 {_x000D_
    display: inline-flex; /* element only as wide as content */_x000D_
}_x000D_
.button.b2 {_x000D_
    display: table; /* element only as wide as content */_x000D_
}
_x000D_
<div class="container c1">_x000D_
  <a class="button b1" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Before And After Wrap</a>_x000D_
</div>_x000D_
<div class="container c2">_x000D_
  <a class="button b2" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Only Before Wrap</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle

https://jsfiddle.net/Hastig/02fbs3pv/

How to strip a specific word from a string?

A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'

Convert Pixels to Points

System.Drawing.Graphics has DpiX and DpiY properties. DpiX is pixels per inch horizontally. DpiY is pixels per inch vertically. Use those to convert from points (72 points per inch) to pixels.

Ex: 14 horizontal points = (14 * DpiX) / 72 pixels

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Make the image go behind the text and keep it in center using CSS

Try this code:

body {z-index:0}
img.center {z-index:-1; margin-left:auto; margin-right:auto}

Setting the left & right margins to auto should center your image.

Twitter Bootstrap modal: How to remove Slide down effect

I have found the best solution that removes the slide but leaves the fade is by adding the following css in a css file of your chosing which is invoked after the bootstrap.css

.modal.fade .modal-dialog 
{
    -moz-transition: none !important;
    -o-transition: none !important;
    -webkit-transition: none !important;
    transition: none !important;

    -moz-transform: none !important;
    -ms-transform: none !important;
    -o-transform: none !important;
    -webkit-transform: none !important;
    transform: none !important;
}

How can I get the client's IP address in ASP.NET MVC?

The simple answer is to use the HttpRequest.UserHostAddress property.

Example: From within a Controller:

using System;
using System.Web.Mvc;

namespace Mvc.Controllers
{
    public class HomeController : ClientController
    {
        public ActionResult Index()
        {
            string ip = Request.UserHostAddress;

            ...
        }
    }
}

Example: From within a helper class:

using System.Web;

namespace Mvc.Helpers
{
    public static class HelperClass
    {
        public static string GetIPHelper()
        {
            string ip = HttpContext.Current.Request.UserHostAddress;
            ..
        }
    }
}

BUT, if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.

Proxy servers MAY use the de facto standard of placing the client's IP address in the X-Forwarded-For HTTP header. Aside from there is no guarantee that a request has a X-Forwarded-For header, there is also no guarantee that the X-Forwarded-For hasn't been SPOOFED.


Original Answer

Request.UserHostAddress

The above code provides the Client's IP address without resorting to looking up a collection. The Request property is available within Controllers (or Views). Therefore instead of passing a Page class to your function you can pass a Request object to get the same result:

public static string getIPAddress(HttpRequestBase request)
{
    string szRemoteAddr = request.UserHostAddress;
    string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
    string szIP = "";

    if (szXForwardedFor == null)
    {
        szIP = szRemoteAddr;
    }
    else
    {
        szIP = szXForwardedFor;
        if (szIP.IndexOf(",") > 0)
        {
            string [] arIPs = szIP.Split(',');

            foreach (string item in arIPs)
            {
                if (!isPrivateIP(item))
                {
                    return item;
                }
            }
        }
    }
    return szIP;
}

Taking screenshot on Emulator from Android Studio

Long Press on Power button, then you will have the option for the screenshot. Power Button Emulator

Option for screenshot in emulator

How to set a parameter in a HttpServletRequest?

The most upvoted solution generally works but for Spring and/or Spring Boot, the values will not wire to parameters in controller methods annotated with @RequestParam unless you specifically implemented getParameterValues(). I combined the solution(s) here and from this blog:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MutableHttpRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> mutableParams = new HashMap<>();

    public MutableHttpRequest(final HttpServletRequest request) {
        super(request);
    }

    public MutableHttpRequest addParameter(String name, String value) {
        if (value != null)
            mutableParams.put(name, new String[] { value });

        return this;
    }

    @Override
    public String getParameter(final String name) {
        String[] values = getParameterMap().get(name);

        return Arrays.stream(values)
                .findFirst()
                .orElse(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> allParameters = new HashMap<>();
        allParameters.putAll(super.getParameterMap());
        allParameters.putAll(mutableParams);

        return Collections.unmodifiableMap(allParameters);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}

note that this code is not super-optimized but it works.

Creating a comma separated list from IList<string> or IEnumerable<string>

I came over this discussion while searching for a good C# method to join strings like it is done with the MySql method CONCAT_WS(). This method differs from the string.Join() method in that it does not add the separator sign if strings are NULL or empty.

CONCAT_WS(', ',tbl.Lastname,tbl.Firstname)

will return only Lastname if firstname is empty, whilst

string.Join(", ", strLastname, strFirstname)

will return strLastname + ", " in the same case.

Wanting the first behavior, I wrote the following methods:

    public static string JoinStringsIfNotNullOrEmpty(string strSeparator, string strA, string strB, string strC = "")
    {
        return JoinStringsIfNotNullOrEmpty(strSeparator, new[] {strA, strB, strC});
    }

    public static string JoinStringsIfNotNullOrEmpty(string strSeparator, string[] arrayStrings)
    {
        if (strSeparator == null)
            strSeparator = "";
        if (arrayStrings == null)
            return "";
        string strRetVal = arrayStrings.Where(str => !string.IsNullOrEmpty(str)).Aggregate("", (current, str) => current + (str + strSeparator));
        int trimEndStartIndex = strRetVal.Length - strSeparator.Length;
        if (trimEndStartIndex>0)
            strRetVal = strRetVal.Remove(trimEndStartIndex);
        return strRetVal;
    }

Mixing C# & VB In The Same Project

Walkthrough: Using Multiple Programming Languages in a Web Site Project http://msdn.microsoft.com/en-us/library/ms366714.aspx

By default, the App_Code folder does not allow multiple programming languages. However, in a Web site project you can modify your folder structure and configuration settings to support multiple programming languages such as Visual Basic and C#. This allows ASP.NET to create multiple assemblies, one for each language. For more information, see Shared Code Folders in ASP.NET Web Projects. Developers commonly include multiple programming languages in Web applications to support multiple development teams that operate independently and prefer different programming languages.

Symfony2 : How to get form validation errors after binding the request to the form

I came up with this solution. It works solid with the latest Symfony 2.4.

I will try to give some explanations.

Using separate validator

I think it's a bad idea to use separate validation to validate entities and return constraint violation messages, like suggested by other writers.

  1. You will need to manually validate all the entities, specify validation groups, etc, etc. With complex hierarchical forms it's not practical at all and will get out of hands quickly.

  2. This way you will be validating form twice: once with form and once with separate validator. This is a bad idea from the performance perspective.

I suggest to recursively iterate form type with it's children to collect error messages.

Using some suggested methods with exclusive IF statement

Some answers suggested by another authors contain mutually exclusive IF statements like this: if ($form->count() > 0) or if ($form->hasChildren()).

As far as I can see, every form can have errors as well as children. I'm not expert with Symfony Forms component, but in practice you will not get some errors of the form itself, like CSRF protection error or extra fields error. I suggest to remove this separation.

Using denormalized result structure

Some authors suggest to put all errors inside of a plain array. So all the error messages of the form itself and of it's children will be added to the same array with different indexing strategies: number-based for type's own errors and name-based for children errors. I suggest to use normalized data structure of the form:

errors:
    - "Self error"
    - "Another self error"

children
    - "some_child":
        errors:
            - "Children error"
            - "Another children error"

        children
            - "deeper_child":
                errors:
                    - "Children error"
                    - "Another children error"

    - "another_child":
        errors:
            - "Children error"
            - "Another children error"

That way result can be easily iterated later.

My solution

So here's my solution to this problem:

use Symfony\Component\Form\Form;

/**
 * @param Form $form
 * @return array
 */
protected function getFormErrors(Form $form)
{
    $result = [];

    // No need for further processing if form is valid.
    if ($form->isValid()) {
        return $result;
    }

    // Looking for own errors.
    $errors = $form->getErrors();
    if (count($errors)) {
        $result['errors'] = [];
        foreach ($errors as $error) {
            $result['errors'][] = $error->getMessage();
        }
    }

    // Looking for invalid children and collecting errors recursively.
    if ($form->count()) {
        $childErrors = [];
        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $childErrors[$child->getName()] = $this->getFormErrors($child);
            }
        }
        if (count($childErrors)) {
            $result['children'] = $childErrors;
        }
    }

    return $result;
}

I hope it'll help someone.

How to get the size of a JavaScript object?

I believe you forgot to include 'array'.

  typeOf : function(value) {
        var s = typeof value;
        if (s === 'object')
        {
            if (value)
            {
                if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function')
                {
                    s = 'array';
                }
            }
            else
            {
                s = 'null';
            }
        }
        return s;
    },

   estimateSizeOfObject: function(value, level)
    {
        if(undefined === level)
            level = 0;

        var bytes = 0;

        if ('boolean' === typeOf(value))
            bytes = 4;
        else if ('string' === typeOf(value))
            bytes = value.length * 2;
        else if ('number' === typeOf(value))
            bytes = 8;
        else if ('object' === typeOf(value) || 'array' === typeOf(value))
        {
            for(var i in value)
            {
                bytes += i.length * 2;
                bytes+= 8; // an assumed existence overhead
                bytes+= estimateSizeOfObject(value[i], 1)
            }
        }
        return bytes;
    },

   formatByteSize : function(bytes)
    {
        if (bytes < 1024)
            return bytes + " bytes";
        else
        {
            var floatNum = bytes/1024;
            return floatNum.toFixed(2) + " kb";
        }
    },

How to determine an object's class?

I use the blow function in my GeneralUtils class, check it may be useful

    public String getFieldType(Object o) {
    if (o == null) {
        return "Unable to identify the class name";
    }
    return o.getClass().getName();
}

Insertion Sort vs. Selection Sort

What they both have in common is that they both use a partition to differentiate between the sorted part of the array and the unsorted.

The difference is, that with selection sort you are guaranteed that sorted part of the array won't change when adding elements to the sorted partition.

The reason being, because selection searches for the minimum of the unsorted set and adds it right after the last element of the sorted set, thereby increasing the sorted set by 1.

Insertion on the other hand, only just cares about the next element that is encountered, which is the first element in the unsorted part of the array. It will take this element and simply fit it into its proper place in the sorted set.

Insertion sort will typically always be a better candidate for arrays that are only partially sorted because you are wasting operations to find the minimum.

Conclusion:

Selection sort incrementally adds an element to the end by finding the minimum element in the unsorted section.

Insertion sort propagates the first element found in the unsorted section into anywhere in the sorted section.

Where is GACUTIL for .net Framework 4.0 in windows 7?

There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.

They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.

Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?

If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.

On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).

Best way to make a shell script daemon?

If I had a script.sh and i wanted to execute it from bash and leave it running even when I want to close my bash session then I would combine nohup and & at the end.

example: nohup ./script.sh < inputFile.txt > ./logFile 2>&1 &

inputFile.txt can be any file. If your file has no input then we usually use /dev/null. So the command would be:

nohup ./script.sh < /dev/null > ./logFile 2>&1 &

After that close your bash session,open another terminal and execute: ps -aux | egrep "script.sh" and you will see that your script is still running at the background. Of cource,if you want to stop it then execute the same command (ps) and kill -9 <PID-OF-YOUR-SCRIPT>

A general tree implementation?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name, self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name, self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

Rails update_attributes without save?

I believe what you are looking for is assign_attributes.

It's basically the same as update_attributes but it doesn't save the record:

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :is_admin, :as => :admin
end

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

Jenkins: Cannot define variable in pipeline stage

The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... } block, but as a result, you'll lose validation of syntax, parameters, etc within the script block.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Downloading jQuery UI CSS from Google's CDN

The Google AJAX Libraries API, which includes jQuery UI (currently v1.10.3), also includes popular themes as per the jQuery UI blog:

Google Ajax Libraries API (CDN)

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
    svm.SVR(),
    linear_model.SGDRegressor(),
    linear_model.BayesianRidge(),
    linear_model.LassoLars(),
    linear_model.ARDRegression(),
    linear_model.PassiveAggressiveRegressor(),
    linear_model.TheilSenRegressor(),
    linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
    print(item)
    clf = item
    clf.fit(trainingData, trainingScores)
    print(clf.predict(predictionData),'\n')

JPA - Returning an auto generated id after persist()

This is how I did it:

EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();

Best way to convert an ArrayList to a string

If you were looking for a quick one-liner, as of Java 5 you can do this:

myList.toString().replaceAll("\\[|\\]", "").replaceAll(", ","\t")

Additionally, if your purpose is just to print out the contents and are less concerned about the "\t", you can simply do this:

myList.toString()

which returns a string like

[str1, str2, str3]

If you have an Array (not ArrayList) then you can accomplish the same like this:

 Arrays.toString(myList).replaceAll("\\[|\\]", "").replaceAll(", ","\t")

Read file from line 2 or skip header row

# Open a connection to the file
with open('world_dev_ind.csv') as file:

    # Skip the column names
    file.readline()

    # Initialize an empty dictionary: counts_dict
    counts_dict = {}

    # Process only the first 1000 rows
    for j in range(0, 1000):

        # Split the current line into a list: line
        line = file.readline().split(',')

        # Get the value for the first column: first_col
        first_col = line[0]

        # If the column value is in the dict, increment its value
        if first_col in counts_dict.keys():
            counts_dict[first_col] += 1

        # Else, add to the dict and set value to 1
        else:
            counts_dict[first_col] = 1

# Print the resulting dictionary
print(counts_dict)

Convert List into Comma-Separated String

static void Main(string[] args){          
List<string> listStrings = new List<string>() { "C#", "Asp.Net", "SQL Server", "PHP", "Angular" };  
string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);  
Console.Write(CommaSeparateString);  
Console.ReadKey();}
private static string GenerateCommaSeparateStringFromList(List<string> listStrings){return String.Join(",", listStrings);}

Convert a list of string to comma separated string C#

MySQL select rows where left join is null

One of the best approach if you do not want to return any columns from table2 is to use the NOT EXISTS

SELECT  table1.id 
FROM    table1 T1
WHERE
  NOT EXISTS (SELECT *
              FROM table2 T2
              WHERE T1.id = T2.user_one
                  OR T1.id = T2.user_two)

Semantically this says what you want to query: Select every row where there is no matching record in the second table.

MySQL is optimized for EXISTS: It returns as soon as it finds the first matching record.

How to add a line break in an Android TextView?

As I know in the previous version of android studio uses separate lines " \n " code. But new one (4.1.2) uses "<br/" to separate lines. For example - Old one:

<string name="string_name">Sample text 1 \n Sample text 2 </string>

New one:

<string name="string_name">Sample text 1 <br/> Sample text 2 </string>

configure: error: C compiler cannot create executables

Ensures the path to Xcode.app bundle is without space or strange characters. I have Xcode installed in ~/Downloads/Last Dev Tools/ folder, so with spaces and renaming the folder to LastDevTools fixed this (after resetting xcode-select -p though)

Could not find method android() for arguments

guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:

Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.

So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.

I solved my problem just follow this steps:

? Copy .aar package in app/libs.

? Add this in app/build.gradle file:

repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):

dependencies {
    compile(name:'package_name', ext:'aar')
}

So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.

How to redirect siteA to siteB with A or CNAME records

You can do this a number of non-DNS ways. The landing page at subdomain.hostone.com can have an HTTP redirect. The webserver at hostone.com can be configured to redirect (easy in Apache, not sure about IIS), etc.

Check if a variable is a string in JavaScript

if (s && typeof s.valueOf() === "string") {
  // s is a string
}

Works for both string literals let s = 'blah' and for Object Strings let s = new String('blah')

Does Java SE 8 have Pairs or Tuples?

Since Java 9, you can create instances of Map.Entry easier than before:

Entry<Integer, String> pair = Map.entry(1, "a");

Map.entry returns an unmodifiable Entry and forbids nulls.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I just ran into this problem with WAMP and the phpMyAdmin that comes with it. To remove the database and make the error go away. I went into C:\wamp\bin\mysql\mysql5.5.24\data\ and deleted the folder for the database in question.

Then I refreshed the page at phpMyAdmin, and the database was gone.

Javascript - How to show escape characters in a string?

JavaScript uses the \ (backslash) as an escape characters for:

  • \' single quote
  • \" double quote
  • \ backslash
  • \n new line
  • \r carriage return
  • \t tab
  • \b backspace
  • \f form feed
  • \v vertical tab (IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v.)
  • \0 null character (U+0000 NULL) (only if the next character is not a decimal digit; else it’s an octal escape sequence)

Note that the \v and \0 escapes are not allowed in JSON strings.

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

Javascript to open popup window and disable parent window

Hi the answer that @anu posted is right, but it wont completely work as required. By making a slight change to child_open() function it works properly.

<html>
<head>
<script type="text/javascript">

var popupWindow=null;

function child_open()
{ 
if(popupWindow && !popupWindow.closed)
   popupWindow.focus();
else
   popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");

}
function parent_disable() {
  if(popupWindow && !popupWindow.closed)
    popupWindow.focus();
}
</script>
</head>
  <body onFocus="parent_disable();" onclick="parent_disable();">
     <a href="javascript:child_open()">Click me</a>
  </body>    
</html>

How to delete columns in pyspark dataframe

You can use two way:

1: You just keep the necessary columns:

drop_column_list = ["drop_column"]
df = df.select([column for column in df.columns if column not in drop_column_list])  

2: This is the more elegant way.

df = df.drop("col_name")

You should avoid the collect() version, because it will send to the master the complete dataset, it will take a big computing effort!

Inline JavaScript onclick function

This isn't really recommended, but you can do it all inline like so:

<a href="#" onClick="function test(){ /* Do something */  } test(); return false;"></a>

But I can't think of any situations off hand where this would be better than writing the function somewhere else and invoking it onClick.

Using XPATH to search text containing &nbsp;

Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&amp;, &gt;, &lt;, &apos;, &quot;) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter &#160; in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.

How to recursively find and list the latest modified files in a directory with subdirectories and times

Both the Perl and Python solutions in this post helped me solve this problem on Mac OS X:

How to list files sorted by modification date recursively (no stat command available!)

Quoting from the post:

Perl:

find . -type f -print |
perl -l -ne '
    $_{$_} = -M;  # store file age (mtime - now)
    END {
        $,="\n";
        print sort {$_{$b} <=> $_{$a}} keys %_;  # print by decreasing age
    }'

Python:

find . -type f -print |
python -c 'import os, sys; times = {}
for f in sys.stdin.readlines(): f = f[0:-1]; times[f] = os.stat(f).st_mtime
for f in sorted(times.iterkeys(), key=lambda f:times[f]): print f'

How to send a POST request with BODY in swift

Here is how I created Http POST request with swift that needs parameters with Json encoding and with headers.

Created API Client BKCAPIClient as a shared instance which will include all types of requests such as POST, GET, PUT, DELETE etc.

func postRequest(url:String, params:Parameters?, headers:HTTPHeaders?, completion:@escaping (_ responseData:Result<Any>?, _ error:Error?)->Void){
    Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON {
        response in
        guard response.result.isSuccess,
            (response.result.value != nil) else {
                debugPrint("Error while fetching data: \(String(describing: response.result.error))")
                completion(nil,response.result.error)
                return
        }
        completion(response.result,nil)
    }
}

Created Operation class that contains all data needed for particular request and also contains parsing logic inside completion block.

func requestAccountOperation(completion: @escaping ( (_ result:Any?, _ error:Error?) -> Void)){
    BKCApiClient.shared.postRequest(url: BKCConstants().bkcUrl, params: self.parametrs(), headers: self.headers()) { (result, error) in
        if(error != nil){
            //Parse and save to DB/Singletons.
        }
        completion(result, error)
    }
}
func parametrs()->Parameters{
    return ["userid”:”xnmtyrdx”,”bcode":"HDF"] as Parameters
}
func headers()->HTTPHeaders{
    return ["Authorization": "Basic bXl1c2VyOm15cGFzcw",
            "Content-Type": "application/json"] as HTTPHeaders
}

Call API In any View Controller where we need this data

func callToAPIOperation(){
let accOperation: AccountRequestOperation = AccountRequestOperation()
accOperation.requestAccountOperation{(result, error) in

}}

What does OpenCV's cvWaitKey( ) function do?

The cvWaitKey simply provides something of a delay. For example:

char c = cvWaitKey(33);
if( c == 27 ) break;

Tis was apart of my code in which a video was loaded into openCV and the frames outputted. The 33 number in the code means that after 33ms, a new frame would be shown. Hence, the was a dely or time interval of 33ms between each frame being shown on the screen. Hope this helps.

How to put a text beside the image?

I had a similar issue, where I had one div holding the image, and one div holding the text. The reason mine wasn't working, was that the div holding the image had display: inline-block while the div holding the text had display: inline.

I changed it to both be display: inline and it worked.

Here's a solution for a basic header section with a logo, title and tagline:

HTML

<div class="site-branding">
  <div class="site-branding-logo">
    <img src="add/Your/URI/Here" alt="what Is The Image About?" />
  </div>
</div>
<div class="site-branding-text">
  <h1 id="site-title">Site Title</h1>
  <h2 id="site-tagline">Site Tagline</h2>
</div>

CSS

div.site-branding { /* Position Logo and Text  */
  display: inline-block;
  vertical-align: middle;
}

div.site-branding-logo { /* Position logo within site-branding */
  display: inline;
  vertical-align: middle;
}

div.site-branding-text { /* Position text within site-branding */
    display: inline;
    width: 350px;
    margin: auto 0;
    vertical-align: middle;
}

div.site-branding-title { /* Position title within text */
    display: inline;
}

div.site-branding-tagline { /* Position tagline within text */
    display: block;
}

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Carousel with Thumbnails in Bootstrap 3.0

  1. Use the carousel's indicators to display thumbnails.
  2. Position the thumbnails outside of the main carousel with CSS.
  3. Set the maximum height of the indicators to not be larger than the thumbnails.
  4. Whenever the carousel has slid, update the position of the indicators, positioning the active indicator in the middle of the indicators.

I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.

Also, my templating engine is smarty, but I'm sure you get the idea.

The meat...

Updating the indicators:

<ol class="carousel-indicators">
    {assign var='walker' value=0}
    {foreach from=$item["imagearray"] key="key" item="value"}
        <li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
            <img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
        </li>

        {assign var='walker' value=1 + $walker}
    {/foreach}
</ol>

Changing the CSS related to the indicators:

.carousel-indicators {
    bottom:-50px;
    height: 36px;
    overflow-x: hidden;
    white-space: nowrap;
}

.carousel-indicators li {
    text-indent: 0;
    width: 34px !important;
    height: 34px !important;
    border-radius: 0;
}

.carousel-indicators li img {
    width: 32px;
    height: 32px;
    opacity: 0.5;
}

.carousel-indicators li:hover img, .carousel-indicators li.active img {
    opacity: 1;
}

.carousel-indicators .active {
    border-color: #337ab7;
}

When the carousel has slid, update the list of thumbnails:

$('#myCarousel').on('slid.bs.carousel', function() {
    var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width(); 
    var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
    var toScroll = newIndicatorPosition + indicatorPosition;
    var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
    if (adjustedScroll < 0)
        adjustedScroll = 0;

    if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
        adjustedScroll = widthEstimate - $(".carousel-indicators").width();

    $('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);

    indicatorPosition = adjustedScroll;
});

And, when your page loads, set the initial scroll position of the thumbnails:

var indicatorPosition = 0;

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

// Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

iOS - Build fails with CocoaPods cannot find header files

If you had the building errors after a "pod install" or a "pod update", it may be that one of your pods have been built with XCode 6.3 while you are still using a previous version.

In my case I had to update my OSX from mavericks to Yosemite to have Xcode 6.3 and solve the problem

OWIN Startup Class Missing

I had this problem, understand this isn't what was wrong in the OP's case, but in my case I did have a Startup class, it just wasn't finding it by default.

My problem was the I had spaces in my Assembly Name, and hence the default namespace was different from assembly name, hence the namespace for the startup class was different than the assembly name.

As the error suggests, by convention it looks for [Assembly Name].Startup for the class... so be sure the namespace for your Startup class is the same as the Assembly name. Fixed the problem for me.

Mock MVC - Add Request Parameter to test

@ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.

(i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

String.equals versus ==

It will also work if you call intern() on the string before inserting it into the array. Interned strings are reference-equal (==) if and only if they are value-equal (equals().)

public static void main (String... aArguments) throws IOException {

String usuario = "Jorman";
String password = "14988611";

String strDatos="Jorman 14988611";
StringTokenizer tokens=new StringTokenizer(strDatos, " ");
int nDatos=tokens.countTokens();
String[] datos=new String[nDatos];
int i=0;

while(tokens.hasMoreTokens()) {
    String str=tokens.nextToken();
    datos[i]= str.intern();            
    i++;
}

//System.out.println (usuario);

if(datos[0]==usuario) {  
     System.out.println ("WORKING");    
}

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

How to continue the code on the next line in VBA

If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2) into cell G2, here is how I did it.

Range("G2")="=sumifs(B2:B10,A2:A10," & _

"F2)"

To split a line of code, add an ampersand, space and underscore.

Implementing two interfaces in a class with same method. Which interface method is overridden?

This was marked as a duplicate to this question https://stackoverflow.com/questions/24401064/understanding-and-solving-the-diamond-problems-in-java

You need Java 8 to get a multiple inheritance problem, but it is still not a diamon problem as such.

interface A {
    default void hi() { System.out.println("A"); }
}

interface B {
    default void hi() { System.out.println("B"); }
}

class AB implements A, B { // won't compile
}

new AB().hi(); // won't compile.

As JB Nizet comments you can fix this my overriding.

class AB implements A, B {
    public void hi() { A.super.hi(); }
}

However, you don't have a problem with

interface D extends A { }

interface E extends A { }

interface F extends A {
    default void hi() { System.out.println("F"); }
}

class DE implement D, E { }

new DE().hi(); // prints A

class DEF implement D, E, F { }

new DEF().hi(); // prints F as it is closer in the heirarchy than A.

How to import a Python class that is in a directory above?

Here's a three-step, somewhat minimalist version of ThorSummoner's answer for the sake of clarity. It doesn't quite do what I want (I'll explain at the bottom), but it works okay.

Step 1: Make directory and setup.py

filepath_to/project_name/
    setup.py

In setup.py, write:

import setuptools

setuptools.setup(name='project_name')

Step 2: Install this directory as a package

Run this code in console:

python -m pip install --editable filepath_to/project_name

Instead of python, you may need to use python3 or something, depending on how your python is installed. Also, you can use -e instead of --editable.

Now, your directory will look more or less like this. I don't know what the egg stuff is.

filepath_to/project_name/
    setup.py
    test_3.egg-info/
        dependency_links.txt
        PKG-INFO
        SOURCES.txt
        top_level.txt

This folder is considered a python package and you can import from files in this parent directory even if you're writing a script anywhere else on your computer.

Step 3. Import from above

Let's say you make two files, one in your project's main directory and another in a sub directory. It'll look like this:

filepath_to/project_name/
    top_level_file.py
    subdirectory/
        subfile.py

    setup.py          |
    test_3.egg-info/  |----- Ignore these guys
        ...           |

Now, if top_level_file.py looks like this:

x = 1

Then I can import it from subfile.py, or really any other file anywhere else on your computer.

# subfile.py  OR  some_other_python_file_somewhere_else.py

import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.

print(top_level_file.x)

This is different than what I was looking for: I hoped python had a one-line way to import from a file above. Instead, I have to treat the script like a module, do a bunch of boilerplate, and install it globally for the entire python installation to have access to it. It's overkill. If anyone has a simpler method than doesn't involve the above process or importlib shenanigans, please let me know.

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

Creating an empty file in C#

To avoid accidentally overwriting an existing file use:

using (new FileStream(filename, FileMode.CreateNew)) {}

...and handle the IOException which will occur if the file already exists.

File.Create, which is suggested in other answers, will overwrite the contents of the file if it already exists. In simple cases you could mitigate this using File.Exists(). However something more robust is necessary in scenarios where multiple threads and/or processes are attempting to create files in the same folder simultaneously.

How to start new line with space for next line in Html.fromHtml for text view in android

Did you try <br/>, <br><br/> or simply \n ? <br> should be supported according to this source, though.

Supported HTML tags

PHP Include for HTML?

I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.

What is best tool to compare two SQL Server databases (schema and data)?

I've used Red Gate's tools and they are superb. However, if you can't spend any money you could try Open DBDiff to compare schemas.

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

ImportError: No module named apiclient.discovery

The same error can be seen if you are creating a Python module and your executing the script after installing it via pip or pipx command. In this case ensure you have declared what the project minimally needs to run correctly into install_requires section of your setup.py file, so in this case:

install_requires=[
    "google-api-python-client>=1.12.3",
    "google-auth-httplib2>=0.0.4",
    "google-auth-oauthlib>=0.4.1"
]

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

In Eclipse :-

  1. Right click -> click on 'add to index'

Add conflict file in staged area

  1. Right Click ->click on commit

Add conflict file in local repository

  1. Pull

You will get all changes (change in remote repository and local repository)

Changes mentioned as Head(<<<<<< HEAD) is your change, Changes mentioned in branch(>>>>>>> branch) is other person change, you can update file accordingly.

  1. Right click ->click on add to index

  2. Right click -> commit and push

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

Can't compare naive and aware datetime.now() <= challenge.datetime_end

You are trying to set the timezone for date_time which already has a timezone. Use replace and astimezone functions.

local_tz = pytz.timezone('Asia/Kolkata')

current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)

How to use background thread in swift?

Multi purpose function for thread

public enum QueueType {
        case Main
        case Background
        case LowPriority
        case HighPriority

        var queue: DispatchQueue {
            switch self {
            case .Main:
                return DispatchQueue.main
            case .Background:
                return DispatchQueue(label: "com.app.queue",
                                     qos: .background,
                                     target: nil)
            case .LowPriority:
                return DispatchQueue.global(qos: .userInitiated)
            case .HighPriority:
                return DispatchQueue.global(qos: .userInitiated)
            }
        }
    }

    func performOn(_ queueType: QueueType, closure: @escaping () -> Void) {
        queueType.queue.async(execute: closure)
    }

Use it like :

performOn(.Background) {
    //Code
}

How to do fade-in and fade-out with JavaScript and CSS

why do that to yourself?

jQuery:

$("#element").fadeOut();
$("#element").fadeIn();

I think that's easier.

www.jquery.com

Most common C# bitwise operations on enums

C++ syntax, assuming bit 0 is LSB, assuming flags is unsigned long:

Check if Set:

flags & (1UL << (bit to test# - 1))

Check if not set:

invert test !(flag & (...))

Set:

flag |= (1UL << (bit to set# - 1))

Clear:

flag &= ~(1UL << (bit to clear# - 1))

Toggle:

flag ^= (1UL << (bit to set# - 1))

Get city name using geolocation

Alternatively you could use my service, https://astroip.co, it is a new Geolocation API:

$.get("https://api.astroip.co/?api_key=1725e47c-1486-4369-aaff-463cc9764026", function(response) {
    console.log(response.geo.city, response.geo.country);
});

AstroIP provides geolocation data together with security datapoints like proxy, TOR nodes and crawlers detection. The API also returns currency, timezones, ASN and company data.

It is a pretty new api with an average response time of 40ms from multiple regions around the world, which positions it in the handful list of super fast Geolocation APIs available.

Big free plan of up to 30,000 requests per month for free is available.

Http 415 Unsupported Media type error with JSON

Some times Charset Metada breaks the json while sending in the request. Better, not use charset=utf8 in the request type.

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

get next sequence value from database using hibernate

You can use Hibernate Dialect API for Database independence as follow

class SequenceValueGetter {
    private SessionFactory sessionFactory;

    // For Hibernate 3
    public Long getId(final String sequenceName) {
        final List<Long> ids = new ArrayList<Long>(1);

        sessionFactory.getCurrentSession().doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                DialectResolver dialectResolver = new StandardDialectResolver();
                Dialect dialect =  dialectResolver.resolveDialect(connection.getMetaData());
                PreparedStatement preparedStatement = null;
                ResultSet resultSet = null;
                try {
                    preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
                    resultSet = preparedStatement.executeQuery();
                    resultSet.next();
                    ids.add(resultSet.getLong(1));
                }catch (SQLException e) {
                    throw e;
                } finally {
                    if(preparedStatement != null) {
                        preparedStatement.close();
                    }
                    if(resultSet != null) {
                        resultSet.close();
                    }
                }
            }
        });
        return ids.get(0);
    }

    // For Hibernate 4
    public Long getID(final String sequenceName) {
        ReturningWork<Long> maxReturningWork = new ReturningWork<Long>() {
            @Override
            public Long execute(Connection connection) throws SQLException {
                DialectResolver dialectResolver = new StandardDialectResolver();
                Dialect dialect =  dialectResolver.resolveDialect(connection.getMetaData());
                PreparedStatement preparedStatement = null;
                ResultSet resultSet = null;
                try {
                    preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
                    resultSet = preparedStatement.executeQuery();
                    resultSet.next();
                    return resultSet.getLong(1);
                }catch (SQLException e) {
                    throw e;
                } finally {
                    if(preparedStatement != null) {
                        preparedStatement.close();
                    }
                    if(resultSet != null) {
                        resultSet.close();
                    }
                }

            }
        };
        Long maxRecord = sessionFactory.getCurrentSession().doReturningWork(maxReturningWork);
        return maxRecord;
    }

}

Groovy Shell warning "Could not open/create prefs root node ..."

Dennis answer is correct. However I would like to explain the solution in a bit more detailed way (for Windows User):

  1. Go into your Start Menu and type regedit into the search field.
  2. Navigate to path HKEY_LOCAL_MACHINE\Software\JavaSoft (Windows 10 seems to now have this here: HKEY_LOCAL_MACHINE\Software\WOW6432Node\JavaSoft)
  3. Right click on the JavaSoft folder and click on New -> Key
  4. Name the new Key Prefs and everything should work.

Alternatively, save and execute a *.reg file with the following content:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs]

What's the difference between a 302 and a 307 redirect?

Flowchart

  • 301: permanent redirect: the URL is old and should be replaced. Browsers will cache this.
    Example usage: URL moved from /register-form.html to signup-form.html.
    The method will change to GET, as per RFC 7231: "For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request."
  • 302: temporary redirect. Only use for HTTP/1.0 clients. This status code should not change the method, but browsers did it anyway. The RFC says: "Many pre-HTTP/1.1 user agents do not understand [303]. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303." Of course, some clients may implement it according to the spec, so if interoperability with such ancient clients is not a real concern, 303 is better for consistent results.
  • 303: temporary redirect, changing the method to GET.
    Example usage: if the browser sent POST to /register.php, then now load (GET) /success.html.
  • 307: temporary redirect, repeating the request identically.
    Example usage: if the browser sent a POST to /register.php, then this tells it to redo the POST at /signup.php.
  • 308: permanent redirect, repeating the request identically. Where 307 is the "no method change" counterpart of 303, this 308 status is the "no method change" counterpart of 301.

RFC 7231 (from 2014) is very readable and not overly verbose. If you want to know the exact answer, it's a recommended read. Some other answers use RFC 2616 from 1999, but nothing changed.

RFC 7238 specifies the 308 status. It is considered experimental, but it was already supported by all major browsers in 2016.

How can I pass arguments to a batch file?

Paired arguments

If you prefer passing the arguments in a key-value pair you can use something like this:

@echo off

setlocal enableDelayedExpansion

:::::  asigning arguments as a key-value pairs:::::::::::::
set counter=0
for %%# in (%*) do (    
    set /a counter=counter+1
    set /a even=counter%%2
    
    if !even! == 0 (
        echo setting !prev! to %%#
        set "!prev!=%%~#"
    )
    set "prev=%%~#"
)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: showing the assignments
echo %one% %two% %three% %four% %five%

endlocal

And an example :

c:>argumentsDemo.bat one 1 "two" 2 three 3 four 4 "five" 5
1 2 3 4 5

Predefined variables

You can also set some environment variables in advance. It can be done by setting them in the console or setting them from my computer:

@echo off

if defined variable1 (
    echo %variable1%
)

if defined variable2 (
    echo %variable2%
)

and calling it like:

c:\>set variable1=1

c:\>set variable2=2

c:\>argumentsTest.bat
1
2

File with listed values

You can also point to a file where the needed values are preset. If this is the script:

@echo off

setlocal
::::::::::
set "VALUES_FILE=E:\scripts\values.txt"
:::::::::::


for /f "usebackq eol=: tokens=* delims=" %%# in ("%VALUES_FILE%") do set "%%#"

echo %key1% %key2% %some_other_key%

endlocal

and values file is this:

:::: use EOL=: in the FOR loop to use it as a comment

key1=value1

key2=value2

:::: do not left spaces arround the =
:::: or at the begining of the line

some_other_key=something else

and_one_more=more

the output of calling it will be:

value1 value2 something else

Of course you can combine all approaches. Check also arguments syntax , shift

How do I call a non-static method from a static method in C#?

Assuming that both data1() and data2() are in the same class, then another alternative is to make data1() static.

private static void data1()
{
}
private static void data2()
{
   data1();
}

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

POST string to ASP.NET Web Api application - returns null

i meet this problem, and find this article. http://www.jasonwatmore.com/post/2014/04/18/Post-a-simple-string-value-from-AngularJS-to-NET-Web-API.aspx

The solution I found was to simply wrap the string value in double quotes in your js post

works like a charm! FYI

How to return JSON data from spring Controller using @ResponseBody

When I was facing this issue, I simply put just getter setter methods and my issues were resolved.

I am using Spring boot version 2.0.

PHP decoding and encoding json with unicode characters

I have found following way to fix this issue... I hope this can help you.

json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

How do I set a textbox's text to bold at run time?

Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.

Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RegisterEvents();
    }

    private void RegisterEvents()
    {
        _tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
    }

    private void TboTest_TextChanged(object sender, EventArgs e)
    {
        // Change the text to bold on specified condition
        if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
        }
        else
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
        }
    }
}

What is the apply function in Scala?

Mathematicians have their own little funny ways, so instead of saying "then we call function f passing it x as a parameter" as we programmers would say, they talk about "applying function f to its argument x".

In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia

apply serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int parameter and returns an Int will have OO type of Function1[Int,Int].

 // define a function in scala
 (x:Int) => x + 1

 // assign an object representing the function to a variable
 val f = (x:Int) => x + 1

Since everything is an object in Scala f can now be treated as a reference to Function1[Int,Int] object. For example, we can call toString method inherited from Any, that would have been impossible for a pure function, because functions don't have methods:

  f.toString

Or we could define another Function1[Int,Int] object by calling compose method on f and chaining two different functions together:

 val f2 = f.compose((x:Int) => x - 1)

Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply method on the Function1[Int,Int] object:

 f2.apply(2)

Writing f.apply(args) every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args). That's where Scala compiler steps in and whenever we have a reference f to a function object and write f (args) to apply arguments to the represented function the compiler silently expands f (args) to the object method call f.apply (args).

Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply method. Such objects can be used in the function notation:

// we will be able to use this object as a function, as well as an object
object Foo {
  var y = 5
  def apply (x: Int) = x + y
}


Foo (1) // using Foo object in function notation 

There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply object to a set of arguments to create a new instance of an associated class:

List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation

// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3) 

So apply method is just a handy way of closing the gap between functions and objects in Scala.

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

How can I install pip on Windows?

The best way I found so far, is just two lines of code:

curl http://python-distribute.org/distribute_setup.py | python
curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

It was tested on Windows 8 with PowerShell, Cmd, and Git Bash (MinGW).

And you probably want to add the path to your environment. It's somewhere like C:\Python33\Scripts.

Pytorch reshape tensor dimension

import torch
>>>a = torch.Tensor([1,2,3,4,5])
>>>a.size()
torch.Size([5])
#use view to reshape

>>>b = a.view(1,a.shape[0])
>>>b
tensor([[1., 2., 3., 4., 5.]])
>>>b.size()
torch.Size([1, 5])
>>>b.type()
'torch.FloatTensor'

Create SQLite database in android

To understand how to use sqlite database in android with best practices see - Android with sqlite database

There are few classes about which you should know and those will help you model your tables and models i.e android.provider.BaseColumns

Below is an example of a table

public class ProductTable implements BaseColumns {
  public static final String NAME = "name";
  public static final String PRICE = "price";
  public static final String TABLE_NAME = "products";

  public static final String CREATE_QUERY = "create table " + TABLE_NAME + " (" +
      _ID + " INTEGER, " +
      NAME + " TEXT, " +
      PRICE + " INTEGER)";

  public static final String DROP_QUERY = "drop table " + TABLE_NAME;
  public static final String SElECT_QUERY = "select * from " + TABLE_NAME;
}

How do I set cell value to Date and apply default Excel date format?

I am writing my answer here because it may be helpful to other readers, who might have a slightly different requirement than the questioner here.

I prepare an .xlsx template; all the cells which will be populated with dates, are already formatted as date cells (using Excel).

I open the .xlsx template using Apache POI and then just write the date to the cell, and it works.

In the example below, cell A1 is already formatted from within Excel with the format [$-409]mmm yyyy, and the Java code is used only to populate the cell.

FileInputStream inputStream = new FileInputStream(new File("Path to .xlsx template"));
Workbook wb = new XSSFWorkbook(inputStream);
Date date1=new Date();
Sheet xlsMainTable = (Sheet) wb.getSheetAt(0);
Row myRow= CellUtil.getRow(0, xlsMainTable);
CellUtil.getCell(myRow, 0).setCellValue(date1);

WHen the Excel is opened, the date is formatted correctly.

How do I get the file extension of a file in Java?

// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

extension should have ".txt" in it when run.

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

Android Studio emulator does not come with Play Store for API 23

I've had to do this recently on the API 23 emulator, and followed this guide. It works for API 23 emulator, so you shouldn't have a problem.

Note: All credit goes to the author of the linked blog post (pyoor). I'm just posting it here in case the link breaks for any reason.

....

Download the GAPPS Package

Next we need to pull down the appropriate Google Apps package that matches our Android AVD version. In this case we’ll be using the 'gapps-lp-20141109-signed.zip' package. You can download that file from BasketBuild here.

[pyoor@localhost]$ md5sum gapps-lp-20141109-signed.zip
367ce76d6b7772c92810720b8b0c931e gapps-lp-20141109-signed.zip

In order to install Google Play, we’ll need to push the following 4 APKs to our AVD (located in ./system/priv-app/):

GmsCore.apk, GoogleServicesFramework.apk, GoogleLoginService.apk, Phonesky.apk

[pyoor@localhost]$ unzip -j gapps-lp-20141109-signed.zip \
system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk \
system/priv-app/GoogleLoginService/GoogleLoginService.apk \
system/priv-app/Phonesky/Phonesky.apk \
system/priv-app/GmsCore/GmsCore.apk -d ./

Push APKs to the Emulator

With our APKs extracted, let’s launch our AVD using the following command.

[pyoor@localhost tools]$ ./emulator @<YOUR_DEVICE_NAME> -no-boot-anim

This may take several minutes the first time as the AVD is created. Once started, we need to remount the AVDs system partition as read/write so that we can push our packages onto the device.

[pyoor@localhost]$ cd ~/android-sdk/platform-tools/
[pyoor@localhost platform-tools]$ ./adb remount

Next, push the APKs to our AVD:

[pyoor@localhost platform-tools]$ ./adb push GmsCore.apk /system/priv-app/
[pyoor@localhost platform-tools]$ ./adb push GoogleServicesFramework.apk /system/priv-app/
[pyoor@localhost platform-tools]$ ./adb push GoogleLoginService.apk /system/priv-app/
[pyoor@localhost platform-tools]$ ./adb push Phonesky.apk /system/priv-app

Profit!

And finally, reboot the emualator using the following commands:

[pyoor@localhost platform-tools]$ ./adb shell stop && ./adb shell start

Once the emulator restarts, we should see the Google Play package appear within the menu launcher. After associating a Google account with this AVD we now have a fully working version of Google Play running under our emulator.

Div Background Image Z-Index Issue

Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

Flutter - Layout a Grid

Use whichever suits your need.

  1. GridView.count(...)

    GridView.count(
      crossAxisCount: 2,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  2. GridView.builder(...)

    GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (_, index) => FlutterLogo(),
      itemCount: 4,
    )
    
  3. GridView(...)

    GridView(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  4. GridView.custom(...)

    GridView.custom(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      childrenDelegate: SliverChildListDelegate(
        [
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
        ],
      ),
    )
    
  5. GridView.extent(...)

    GridView.extent(
      maxCrossAxisExtent: 400,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    

Output (same for all):

enter image description here

What's the difference between Apache's Mesos and Google's Kubernetes

Mesos and Kubernetes both are container orchestration tools.

When you say "Google Kubernetes"?

Google Kubernetes Engine provides a managed environment for deploying, managing, and scaling your containerized applications using Google infrastructure.

Kubernetes is an open-source system for automating deployment, scaling, and management of containerized applications.” Kubernetes was built by Google based on their experience running containers in production over the last decade.

The major components in a Kubernetes cluster are:

pods — a way to group containers together replication controllers — a way to handle the lifecycle of containers labels — a way to find and query containers, and services — a set of containers performing a common function

Mesos is an open-source cluster management project by Apache, designed to scale to very large clusters, from hundreds to thousands of hosts. Mesos supports diverse kinds of workloads such as Hadoop tasks, cloud native applications etc. It gives you the ability to run both containerized, and non-containerized workloads in a distributed manner.

It was initially written as a research project at Berkeley and was later adopted by Twitter as an answer to Google’s Borg (Kubernetes’ predecessor). To combat its high degree of complexity (Mesos is super complicated and hard to manage!), Mesosphere came into the picture to try and make Mesos into something regular human beings can use.

Mesosphere supplied the superb Marathon “plugin” to Mesos, which provides users with an easy way to manage container orchestration over Mesos.

In mid-2016, DC/OS (Data Center Operating System) — an open source project backed by Mesosphere — was introduced, which simplifies Mesos even further and allows you to deploy your own Mesos cluster, with Marathon, in a matter of minutes.

Now, if we compare kubernetes and Mesos(DC/OS)

kubernetes is a cluster manager for containers while mesos is a distributed system kernel that will make your cluster look like one giant computer system to all supported frameworks and apps that are built to be run on mesos.

Mesos was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application runs very well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps.

Mesos cluster also runs alongside the Marathon cluster. Marathon, created by Mesosphere, is designed to start, monitor and scale long-running applications, including cloud native apps. Clients interact with Marathon through a REST API.

Also, a point to be noted is that you can actually run Kubernetes on top of DC/OS and schedule containers with it instead of using Marathon. This implies the biggest difference of all — DC/OS, as it name suggests, is more similar to an operating system rather than an orchestration framework. You can run non-containerized, stateful workloads on it. Container scheduling is handled by the Marathon.

How can I schedule a daily backup with SQL Server Express?

You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:

"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"

How to find out which JavaScript events fired?

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

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

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

Source: Firebug Tip: Log Events

Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.

This is the same question as Failed to connect to mailserver at "localhost" port 25

also check this php mail function not working

NOT IN vs NOT EXISTS

If the execution planner says they're the same, they're the same. Use whichever one will make your intention more obvious -- in this case, the second.

'gulp' is not recognized as an internal or external command

You need to make sure, when you run command (install npm -g gulp), it will create install gulp on C:\ directory.

that directory should match with whatver npm path variable set in your java path.

just run path from command prompt, and verify this. if not, change your java class path variable wherever you gulp is instaled.

It should work.

How to update a value, given a key in a hashmap?

It may be little late but here are my two cents.

If you are using Java 8 then you can make use of computeIfPresent method. If the value for the specified key is present and non-null then it attempts to compute a new mapping given the key and its current mapped value.

final Map<String,Integer> map1 = new HashMap<>();
map1.put("A",0);
map1.put("B",0);
map1.computeIfPresent("B",(k,v)->v+1);  //[A=0, B=1]

We can also make use of another method putIfAbsent to put a key. If the specified key is not already associated with a value (or is mapped to null) then this method associates it with the given value and returns null, else returns the current value.

In case the map is shared across threads then we can make use of ConcurrentHashMap and AtomicInteger. From the doc:

An AtomicInteger is an int value that may be updated atomically. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.

We can use them as shown:

final Map<String,AtomicInteger> map2 = new ConcurrentHashMap<>();
map2.putIfAbsent("A",new AtomicInteger(0));
map2.putIfAbsent("B",new AtomicInteger(0)); //[A=0, B=0]
map2.get("B").incrementAndGet();    //[A=0, B=1]

One point to observe is we are invoking get to get the value for key B and then invoking incrementAndGet() on its value which is of course AtomicInteger. We can optimize it as the method putIfAbsent returns the value for the key if already present:

map2.putIfAbsent("B",new AtomicInteger(0)).incrementAndGet();//[A=0, B=2]

On a side note if we plan to use AtomicLong then as per documentation under high contention expected throughput of LongAdder is significantly higher, at the expense of higher space consumption. Also check this question.

Checking whether a String contains a number value in Java

Using a loop -

public static boolean containsDigit(final String aString)
{
    if (aString != null && !aString.isEmpty())
    {
        for (char c : aString.toCharArray())
        {
            if (Character.isDigit(c))
            {
                return true;
            }
        }
    }

    return false;
}

Using a stream -

public static boolean containsDigit(final String aString)
{
    return aString != null && !aString.isEmpty() &&
            aString.chars().anyMatch(Character::isDigit);
}

How to do one-liner if else statement?

One possible way to do this in just one line by using a map, simple I am checking whether a > b if it is true I am assigning c to a otherwise b

c := map[bool]int{true: a, false: b}[a > b]

However, this looks amazing but in some cases it might NOT be the perfect solution because of evaluation order. For example, if I am checking whether an object is not nil get some property out of it, look at the following code snippet which will panic in case of myObj equals nil

type MyStruct struct {
   field1 string
   field2 string 
}

var myObj *MyStruct
myObj = nil 

myField := map[bool]string{true: myObj.field1, false: "empty!"}[myObj != nil}

Because map will be created and built first before evaluating the condition so in case of myObj = nil this will simply panic.

Not to forget to mention that you can still do the conditions in just one simple line, check the following:

var c int
...
if a > b { c = a } else { c = b}

How to add a second x-axis in matplotlib

From matplotlib 3.1 onwards you may use ax.secondary_xaxis

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1,13, num=301)
y = (np.sin(x)+1.01)*3000

# Define function and its inverse
f = lambda x: 1/(1+x)
g = lambda x: 1/x-1

fig, ax = plt.subplots()
ax.semilogy(x, y, label='DM')

ax2 = ax.secondary_xaxis("top", functions=(f,g))

ax2.set_xlabel("1/(x+1)")
ax.set_xlabel("x")
plt.show()

jQuery UI Accordion Expand/Collapse All

Yes, it is possible. Put all div in separate accordion class as follows:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>

<script type="text/javascript">

        $(function () {
            $("input[type=submit], button")
        .button()
        .click(function (event) {
            event.preventDefault();
        });
            $("#tabs").tabs();
            $(".accordion").accordion({
                heightStyle: "content",

                collapsible: true,
                active: 0



            });
        });

function expandAll()
{
  $(".accordion").accordion({
                heightStyle: "content",

                collapsible: true,
                active: 0

            });

            return false;   
}

function collapseAll()
{
  $(".accordion").accordion({
                heightStyle: "content",

                collapsible: true,
                active: false



            });
            return false;
}
</script>



<div class="accordion">
  <h3>Toggle 1</h3>
  <div >
    <p>text1.</p>
  </div>
</div>
<div class="accordion">
  <h3>Toggle 2</h3>
  <div >
    <p>text2.</p>
  </div>
</div>
<div class="accordion">
  <h3>Toggle 3</h3>
  <div >
    <p>text3.</p>
  </div>
</div>

unexpected T_VARIABLE, expecting T_FUNCTION

put public, protected or private before the $connection.

Indentation Error in Python

In Notepad++

View --->Show Symbols --->Show White Spaces and Tabs(select)

replace all tabs with spaces.

Insert HTML from CSS

An alternative - which may work for you depending on what you're trying to do - is to have the HTML in place and then use the CSS to show or hide it depending on the class of a parent element.

OR

Use jQuery append()

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

Essentially it means you don't have the index you are trying to reference. For example:

df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)

will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:

df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)

Hope that answers your question!

CSS Inset Borders

I don't know what you are comparing to.

But a super simple way to have a border look inset when compared to other non-bordered items is to add a border: ?px solid transparent; to whatever items do not have a border.

It will make the bordered item look inset.

http://jsfiddle.net/cmunns/cgrtd/

How do I connect to my existing Git repository using Visual Studio Code?

Use the Git GUI in the Git plugin.

Clone your online repository with the URL which you have.

After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.

Fetch from the remote (to check if anything is updated while you are working).

If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.

Push your changes to the upstream remote repository by making a push operation.

How can I properly use a PDO object for a parameterized SELECT query

A litle bit complete answer is here with all ready for use:

    $sql = "SELECT `username` FROM `users` WHERE `id` = :id";
    $q = $dbh->prepare($sql);
    $q->execute(array(':id' => "4"));
    $done= $q->fetch();

 echo $done[0];

Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();

I hope this help someone, Enjoy!

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

How to get a value of an element by name instead of ID

$('[name=whatever]').val()

The jQuery documentation is your friend.

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

Use of def, val, and var in scala

With

def person = new Person("Kumar", 12) 

you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.

When writing

person.age = 45

you assign a new value to the age property in class Person, which is valid since age is declared as var. The compiler will complain if you try to reassign person with a new Person object like

person = new Person("Steve", 13)  // Error

clear table jquery

I needed this:

$('#myTable tbody > tr').remove();

It deletes all rows except the header.

Run class in Jar file

You want:

java -cp myJar.jar myClass

The Documentation gives the following example:

C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Change selected value of kendo ui dropdownlist

Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.

Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.

To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.

@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
    .Name("Status.StatusId")
    .DataTextField("StatusName")
    .DataValueField("StatusId")
    .BindTo(...)
)

//So that your ViewModel gets bound properly on the post, naming is a bit 
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');    

ddl.select(function(dataItem) {
    return dataItem.StatusName === "Active";
});

Load an image from a url into a PictureBox

Try this:

var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");

using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
    pictureBox1.Image = Bitmap.FromStream(stream);
}

Reading PDF content with itextsharp dll in VB.NET or C#

LGPL / FOSS iTextSharp 4.x

var pdfReader = new PdfReader(path); //other filestream etc
byte[] pageContent = _pdfReader .GetPageContent(pageNum); //not zero based
byte[] utf8 = Encoding.Convert(Encoding.Default, Encoding.UTF8, pageContent);
string textFromPage = Encoding.UTF8.GetString(utf8);

None of the other answers were useful to me, they all seem to target the AGPL v5 of iTextSharp. I could never find any reference to SimpleTextExtractionStrategy or LocationTextExtractionStrategy in the FOSS version.

Something else that might be very useful in conjunction with this:

const string PdfTableFormat = @"\(.*\)Tj";
Regex PdfTableRegex = new Regex(PdfTableFormat, RegexOptions.Compiled);

List<string> ExtractPdfContent(string rawPdfContent)
{
    var matches = PdfTableRegex.Matches(rawPdfContent);

    var list = matches.Cast<Match>()
        .Select(m => m.Value
            .Substring(1) //remove leading (
            .Remove(m.Value.Length - 4) //remove trailing )Tj
            .Replace(@"\)", ")") //unencode parens
            .Replace(@"\(", "(")
            .Trim()
        )
        .ToList();
    return list;
}

This will extract the text-only data from the PDF if the text displayed is Foo(bar) it will be encoded in the PDF as (Foo\(bar\))Tj, this method would return Foo(bar) as expected. This method will strip out lots of additional information such as location coordinates from the raw pdf content.

jquery get height of iframe content when loaded

The less complicated answer is to use .contents() to get at the iframe. Interestingly, though, it returns a different value from what I get using the code in my original answer, due to the padding on the body, I believe.

$('iframe').contents().height() + 'is the height'

This is how I've done it for cross-domain communication, so I'm afraid it's maybe unnecessarily complicated. First, I would put jQuery inside the iFrame's document; this will consume more memory, but it shouldn't increase load time as the script only needs to be loaded once.

Use the iFrame's jQuery to measure the height of your iframe's body as early as possible (onDOMReady) and then set the URL hash to that height. And in the parent document, add an onload event to the iFrame tag that will look at the location of the iframe and extract the value you need. Because onDOMReady will always occur before the document's load event, you can be fairly certain the value will get communicated correctly without a race condition complicating things.

In other words:

...in Help.php:

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552
    }
};
$(getDocumentHeight);

...and in the parent document:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );

How to concat string + i?

Let me add another solution:

>> N = 5;
>> f = cellstr(num2str((1:N)', 'f%d'))
f = 
    'f1'
    'f2'
    'f3'
    'f4'
    'f5'

If N is more than two digits long (>= 10), you will start getting extra spaces. Add a call to strtrim(f) to get rid of them.


As a bonus, there is an undocumented built-in function sprintfc which nicely returns a cell arrays of strings:

>> N = 10;
>> f = sprintfc('f%d', 1:N)
f = 
    'f1'    'f2'    'f3'    'f4'    'f5'    'f6'    'f7'    'f8'    'f9'    'f10'

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

This type of solution did the trick for me:

Parent original = db.Parent.SingleOrDefault<Parent>(t => t.ID == updated.ID);
db.Childs.RemoveRange(original.Childs);
updated.Childs.ToList().ForEach(c => original.Childs.Add(c));
db.Entry<Parent>(original).CurrentValues.SetValues(updated);

Its important to say that this deletes all the records and insert them again. But for my case (less then 10) it´s ok.

I hope it helps.

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None
nop()

Sometimes I do stuff like this when I'm making dependencies optional:

try:
    import foo
    bar=foo.bar
    baz=foo.baz
except:
    bar=nop
    baz=nop

# Doesn't break when foo is missing:
bar()
baz()

Having both a Created and Last Updated timestamp columns in MySQL 4.0

This is how can you have automatic & flexible createDate/lastModified fields using triggers:

First define them like this:

CREATE TABLE `entity` (
  `entityid` int(11) NOT NULL AUTO_INCREMENT,
  `createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `lastModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `name` varchar(255) DEFAULT NULL,
  `comment` text,
  PRIMARY KEY (`entityid`),
)

Then add these triggers:

DELIMITER ;;
CREATE trigger entityinsert BEFORE INSERT ON entity FOR EACH ROW BEGIN SET NEW.createDate=IF(ISNULL(NEW.createDate) OR NEW.createDate='0000-00-00 00:00:00', CURRENT_TIMESTAMP, IF(NEW.createDate<CURRENT_TIMESTAMP, NEW.createDate, CURRENT_TIMESTAMP));SET NEW.lastModified=NEW.createDate; END;;
DELIMITER ;
CREATE trigger entityupdate BEFORE UPDATE ON entity FOR EACH ROW SET NEW.lastModified=IF(NEW.lastModified<OLD.lastModified, OLD.lastModified, CURRENT_TIMESTAMP);
  • If you insert without specifying createDate or lastModified, they will be equal and set to the current timestamp.
  • If you update them without specifying createDate or lastModified, the lastModified will be set to the current timestamp.

But here's the nice part:

  • If you insert, you can specify a createDate older than the current timestamp, allowing imports from older times to work well (lastModified will be equal to createDate).
  • If you update, you can specify a lastModified older than the previous value ('0000-00-00 00:00:00' works well), allowing to update an entry if you're doing cosmetic changes (fixing a typo in a comment) and you want to keep the old lastModified date. This will not modify the lastModified date.

How to verify that a specific method was not called using Mockito?

Use the second argument on the Mockito.verify method, as in:

Mockito.verify(dependency, Mockito.times(0)).someMethod()

In Subversion can I be a user other than my login name?

Most Subversion commands take the --username option to specify the username you want to use to the repository. Subversion remembers the last repository username and password used in each working copy, which means, among other things, that if you use svn checkout --username myuser you never need to specify the username again.

As Kamil Kisiel says, when Subversion is accessing the repository directly off the file system (that is, the repository URL is of form file:///path/to/repo or file://file-server/path/to/repo), it uses your file system permissions to access the repository. And when you connect via SSH tunneling (svn+ssh://server/path/to/repo), SVN uses your FS permissions on the server, as determined by your SSH login. In those cases, svn checkout --username may not work for your repository.

Spring Boot application as a Service

AS A WINDOWS SERVICE

If you want this to run in windows machine download the winsw.exe from

 http://repo.jenkins-ci.org/releases/com/sun/winsw/winsw/2.1.2/

After that rename it to jar filename (eg: your-app.jar)

winsw.exe -> your-app.exe

Now create an xml file your-app.xml and copy the following content to that

<?xml version="1.0" encoding="UTF-8"?>
<service>
     <id>your-app</id>
     <name>your-app</name>
     <description>your-app as a Windows Service</description>
     <executable>java</executable>
     <arguments>-jar "your-app.jar"</arguments>
     <logmode>rotate</logmode>
</service>

Make sure that the exe and xml along with jar in a same folder.

After this open command prompt in Administrator previlege and install it to the windows service.

your-app.exe install
eg -> D:\Springboot\your-app.exe install

If it fails with

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.

Then try the following:

Delete java.exe, javaw.exe and javaws.exe from C:\Windows\System32

thats it :) .

To uninstall the service in windows

your-app.exe uninstall

For see/run/stop service: win+r and type Administrative tools then select the service from that. Then right click choose the option - run / stop

Javascript replace all "%20" with a space

If you want to use jQuery you can use .replaceAll()

How do you use the Immediate Window in Visual Studio?

The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.

To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I

enter image description here

Here is an example with Immediate Window:

int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}

add breakpoint

enter image description here

call commands

enter image description here

https://msdn.microsoft.com/en-us/library/f177hahy.aspx

How do you delete an ActiveRecord object?

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

How to run script as another user without password?

try running:

su -c "Your command right here" -s /bin/sh username

This will run the command as username given that you have permissions to sudo as that user.

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

Echo tab characters in bash script

Using echo to print values of variables is a common Bash pitfall. Reference link:

http://mywiki.wooledge.org/BashPitfalls#echo_.24foo

How to correctly assign a new string value?

Think of strings as abstract objects, and char arrays as containers. The string can be any size but the container must be at least 1 more than the string length (to hold the null terminator).

C has very little syntactical support for strings. There are no string operators (only char-array and char-pointer operators). You can't assign strings.

But you can call functions to help achieve what you want.

The strncpy() function could be used here. For maximum safety I suggest following this pattern:

strncpy(p.name, "Jane", 19);
p.name[19] = '\0'; //add null terminator just in case

Also have a look at the strncat() and memcpy() functions.

What is /dev/null 2>&1?

Edit /etc/conf.apf. Set DEVEL_MODE="0". DEVEL_MODE set to 1 will add a cron job to stop apf after 5 minutes.

jQuery: Clearing Form Inputs

I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

if ($_POST['action'] == 'addRunner') 

I used the :not() on the selection to stop it from clearing the hidden field.

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

Can Selenium WebDriver open browser windows silently in the background?

Use it ...

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

How to make a div center align in HTML

how about something along these lines

<style type="text/css">
  #container {
    margin: 0 auto;
    text-align: center; /* for IE */
  }

  #yourdiv {
    width: 400px;
    border: 1px solid #000;
  }
</style>

....

<div id="container">
  <div id="yourdiv">
    weee
  </div>
</div>

How to set "style=display:none;" using jQuery's attr method?

You can use the jquery attr() method to achieve the setting of teh attribute and the method removeAttr() to delete the attribute for your element msform As seen in the code

$('#msform').attr('style', 'display:none;');


$('#msform').removeAttr('style');

How do you get a directory listing in C?

GLib is a portability/utility library for C which forms the basis of the GTK+ graphical toolkit. It can be used as a standalone library.

It contains portable wrappers for managing directories. See Glib File Utilities documentation for details.

Personally, I wouldn't even consider writing large amounts of C-code without something like GLib behind me. Portability is one thing, but it's also nice to get data structures, thread helpers, events, mainloops etc. for free

Jikes, I'm almost starting to sound like a sales guy :) (don't worry, glib is open source (LGPL) and I'm not affiliated with it in any way)

PostgreSQL: export resulting data from SQL query to Excel/CSV

The correct script for postgres (Ubuntu) is:

COPY (SELECT * FROM tbl) TO '/var/lib/postgres/myfile1.csv';

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I had the same problem into my Spring Boot+Spring Data project when invoking to a @RepositoryRestResource.

The problem is the MIME type returned; which is application/hal+json. Adding it to the server.compression.mime-types property solved this problem for me.

Hope this helps to someone else!

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

If you are just interested in the use of Access-Control-Allow-Origin:*

You can do that with this .htaccess file at the site root.

Header set Access-Control-Allow-Origin "*"

Some useful information here: http://enable-cors.org/server_apache.html

Php $_POST method to get textarea value

Try to use different id and name parameters, currently you have same here. Please visit the link below for the same, this might be help you :

Issue using $_POST with a textarea

How do I vertically center an H1 in a div?

I've had success putting text within span tags and then setting vertical-align: middle on that span. Don't know how cross-browser compliant this is though, I've only tested it in webkit browsers.

Multiple glibc libraries on a single host

If you look closely at the second output you can see that the new location for the libraries is used. Maybe there are still missing libraries that are part of the glibc.

I also think that all the libraries used by your program should be compiled against that version of glibc. If you have access to the source code of the program, a fresh compilation appears to be the best solution.

Entity framework self referencing loop detected

I only had one model i wanted to use, so i ended up with the following code:

var JsonImageModel = Newtonsoft.Json.JsonConvert.SerializeObject(Images, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

How do I pass a class as a parameter in Java?

As you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as gwt-ent for reflection suppport at gwt layer.

HTML/Javascript: how to access JSON data loaded in a script tag with src set

You can't load JSON like that, sorry.

I know you're thinking "why I can't I just use src here? I've seen stuff like this...":

<script id="myJson" type="application/json">
 { 
   name: 'Foo' 
 }
</script>

<script type="text/javascript">
    $(function() {
        var x = JSON.parse($('#myJson').html());
        alert(x.name); //Foo
     });
</script>

... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.

You have a short list of options to load your JSON from a remote file:

  1. Use $.get('your.json') or some other such AJAX method.
  2. Write a file that sets a global variable to your json. (seems hokey).
  3. Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
  4. Consult a voodoo priest.

Final point:

Remote JSON Request after page loads is also not an option, in case you want to suggest that.

... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.

Is there a /dev/null on Windows?

Jon Skeet is correct. Here is the Nul Device Driver page in the Windows Embedded documentation (I have no idea why it's not somewhere else...).

Here is another:

How do you get the length of a string?

In some cases String.length might return a value which is different from the actual number of characters visible on the screen (e.g. some emojis are encoded by 2 UTF-16 units):

MDN says: This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.

Hide Spinner in Input Number - Firefox 29

This worked for me:

    input[type='number'] {
    appearance: none;
}

Solved in Firefox, Safari, Chrome. Also, -moz-appearance: textfield; is not supported anymore (https://developer.mozilla.org/en-US/docs/Web/CSS/appearance)

Java web start - Unable to load resource

this also worked for me , thanks a lot

changing java proxy settings to direct connection did not fix my issue.

What worked for me:

Run "Configure Java" as administrator.
Go to Advanced
Scroll to bottom
Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"
Save

*.h or *.hpp for your class definitions

I use .h because that's what Microsoft uses, and what their code generator creates. No need to go against the grain.

kill a process in bash

try kill -9 {processID}

To find the process ID you can use ps -ef | grep gedit

Make a VStack fill the width of the screen in SwiftUI

One more alternative is to place one of the subviews inside of an HStack and place a Spacer() after it:

struct ContentView : View {
    var body: some View {
        VStack(alignment: .leading) {

            HStack {
                Text("Title")
                    .font(.title)
                    .background(Color.yellow)
                Spacer()
            }

            Text("Content")
                .lineLimit(nil)
                .font(.body)
                .background(Color.blue)

            Spacer()
            }

            .background(Color.red)
    }
}

resulting in :

HStack inside a VStack

How to recursively download a folder via FTP on Linux

You should not use ftp. Like telnet it is not using secure protocols, and passwords are transmitted in clear text. This makes it very easy for third parties to capture your username and password.

To copy remote directories remotely, these options are better:

  • rsync is the best-suited tool if you can login via ssh, because it copies only the differences, and can easily restart in the middle in case the connection breaks.

  • ssh -r is the second-best option to recursively copy directory structures.

See:

changing kafka retention period during runtime

The correct config key is retention.ms

$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".

Command to collapse all sections of code?

None of these worked for me. What I found was, in the editor, search the Keyboard Shortcuts file for editor.foldRecursively. That will give you the latest binding. In my case it was CMD + K, CMD + [.

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

Stack, Static, and Heap in C++

Stack memory allocation (function variables, local variables) can be problematic when your stack is too "deep" and you overflow the memory available to stack allocations. The heap is for objects that need to be accessed from multiple threads or throughout the program lifecycle. You can write an entire program without using the heap.

You can leak memory quite easily without a garbage collector, but you can also dictate when objects and memory is freed. I have run in to issues with Java when it runs the GC and I have a real time process, because the GC is an exclusive thread (nothing else can run). So if performance is critical and you can guarantee there are no leaked objects, not using a GC is very helpful. Otherwise it just makes you hate life when your application consumes memory and you have to track down the source of a leak.

HTML5 tag for horizontal line break

You can still use <hr> as a horizontal line, and you probably should. In HTML5 it defines a thematic break in content, without making any promises about how it is displayed. The attributes that aren't supported in the HTML5 spec are all related to the tag's appearance. The appearance should be set in CSS, not in the HTML itself.

So use the <hr> tag without attributes, then style it in CSS to appear the way you want.

How to get height of Keyboard?

I uses below code,

override func viewDidLoad() {
    super.viewDidLoad()
    self.registerObservers()
}

func registerObservers(){

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

@objc func keyboardWillAppear(notification: Notification){
    if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight)
    }
}

@objc func keyboardWillHide(notification: Notification){
        self.view.transform = .identity
}

How to maximize a plt.show() window using Python

My best effort so far, supporting different backends:

from platform import system
def plt_maximize():
    # See discussion: https://stackoverflow.com/questions/12439588/how-to-maximize-a-plt-show-window-using-python
    backend = plt.get_backend()
    cfm = plt.get_current_fig_manager()
    if backend == "wxAgg":
        cfm.frame.Maximize(True)
    elif backend == "TkAgg":
        if system() == "win32":
            cfm.window.state('zoomed')  # This is windows only
        else:
            cfm.resize(*cfm.window.maxsize())
    elif backend == 'QT4Agg':
        cfm.window.showMaximized()
    elif callable(getattr(cfm, "full_screen_toggle", None)):
        if not getattr(cfm, "flag_is_max", None):
            cfm.full_screen_toggle()
            cfm.flag_is_max = True
    else:
        raise RuntimeError("plt_maximize() is not implemented for current backend:", backend)

How to check for a valid URL in Java?

Consider using the Apache Commons UrlValidator class

UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");

There are several properties that you can set to control how this class behaves, by default http, https, and ftp are accepted.

Extracting substrings in Go

To avoid a panic on a zero length input, wrap the truncate operation in an if

input, _ := src.ReadString('\n')
var inputFmt string
if len(input) > 0 {
    inputFmt = input[:len(input)-1]
}
// Do something with inputFmt

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Getting activity from context in android

an Activity is a specialization of Context so, if you have a Context you already know which activity you intend to use and can simply cast a into c; where a is an Activity and c is a Context.

Activity a = (Activity) c;

MySQL vs MySQLi when using PHP

There is a manual page dedicated to help choosing between mysql, mysqli and PDO at

The PHP team recommends mysqli or PDO_MySQL for new development:

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

The page also has a feature matrix comparing the extension APIs. The main differences between mysqli and mysql API are as follows:

                               mysqli     mysql
Development Status             Active     Maintenance only
Lifecycle                      Active     Long Term Deprecation Announced*
Recommended                    Yes        No
OOP API                        Yes        No
Asynchronous Queries           Yes        No
Server-Side Prep. Statements   Yes        No
Stored Procedures              Yes        No
Multiple Statements            Yes        No
Transactions                   Yes        No
MySQL 5.1+ functionality       Yes        No

* http://news.php.net/php.internals/53799

There is an additional feature matrix comparing the libraries (new mysqlnd versus libmysql) at

and a very thorough blog article at

git recover deleted file where no commit was made after the delete

The output tells you what you need to do. git reset HEAD cc.properties etc.

This will unstage the rm operation. After that, running a git status again will tell you that you need to do a git checkout -- cc.properties to get the file back.

Update: I have this in my config file

$ git config alias.unstage
reset HEAD

which I usually use to unstage stuff.