Programs & Examples On #Scale

The scale tag is mostly used for questions that relate to proportional resizing of images or UI elements. It is also used for questions related to function scale() in R language.

How can I shrink the drawable on a button?

My DiplayScaleHelper, that works perfectly:

import android.content.Context;
import android.widget.Button;

public class DisplayHelper {

  public static void scaleButtonDrawables(Button btn, double fitFactor) {
        Drawable[] drawables = btn.getCompoundDrawables();

        for (int i = 0; i < drawables.length; i++) {
            if (drawables[i] != null) {
                if (drawables[i] instanceof ScaleDrawable) {
                drawables[i].setBounds(0, 0, (int) (drawables[i].getIntrinsicWidth() * fitFactor),
                    (int) (drawables[i].getIntrinsicHeight() * fitFactor));
                ScaleDrawable sd = new ScaleDrawable(drawables[i], 0, drawables[i].getIntrinsicWidth(), drawables[i].getIntrinsicHeight());
                if(i == 0) {
                    btn.setCompoundDrawables(sd.getDrawable(), drawables[1], drawables[2], drawables[3]);
                } else if(i == 1) {
                    btn.setCompoundDrawables(drawables[0], sd.getDrawable(), drawables[2], drawables[3]);
                } else if(i == 2) {
                    btn.setCompoundDrawables(drawables[0], drawables[1], sd.getDrawable(), drawables[3]);
                } else {
                    btn.setCompoundDrawables(drawables[0], drawables[1], drawables[2], sd.getDrawable());

Plot logarithmic axes with matplotlib in python

First of all, it's not very tidy to mix pylab and pyplot code. What's more, pyplot style is preferred over using pylab.

Here is a slightly cleaned up code, using only pyplot functions:

from matplotlib import pyplot

a = [ pow(10,i) for i in range(10) ]

pyplot.plot(a, color='blue', lw=2)

The relevant function is pyplot.yscale(). If you use the object-oriented version, replace it by the method Axes.set_yscale(). Remember that you can also change the scale of X axis, using pyplot.xscale() (or Axes.set_xscale()).

Check my question What is the difference between ‘log’ and ‘symlog’? to see a few examples of the graph scales that matplotlib offers.

Auto Scale TextView Text to Fit within Bounds

This solutions works for us:

public class CustomFontButtonTextFit extends CustomFontButton
    private final float DECREMENT_FACTOR = .1f;

    public CustomFontButtonTextFit(Context context) {

    public CustomFontButtonTextFit(Context context, AttributeSet attrs) {
        super(context, attrs);

    public CustomFontButtonTextFit(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);

    private synchronized void refitText(String text, int textWidth) {
        if (textWidth > 0) 
            float availableWidth = textWidth - this.getPaddingLeft()
                    - this.getPaddingRight();

            TextPaint tp = getPaint();
            Rect rect = new Rect();
            tp.getTextBounds(text, 0, text.length(), rect);
            float size = rect.width();

            while(size > availableWidth)
                setTextSize( getTextSize() - DECREMENT_FACTOR );
                tp = getPaint();

                tp.getTextBounds(text, 0, text.length(), rect);
                size = rect.width();

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int parentHeight = MeasureSpec.getSize(heightMeasureSpec);

        refitText(this.getText().toString(), parentWidth);

        if(parentWidth < getSuggestedMinimumWidth())
            parentWidth = getSuggestedMinimumWidth();

        if(parentHeight < getSuggestedMinimumHeight())
            parentHeight = getSuggestedMinimumHeight();

        this.setMeasuredDimension(parentWidth, parentHeight);

    protected void onTextChanged(final CharSequence text, final int start,
            final int before, final int after) 
        super.onTextChanged(text, start, before, after);

        refitText(text.toString(), this.getWidth());

    protected void onSizeChanged(int w, int h, int oldw, int oldh)
        super.onSizeChanged(w, h, oldw, oldh);

        if (w != oldw) 
            refitText(this.getText().toString(), w);

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).

I was looking through this post for how to do it, and finally did what I want, not the way described here though.

<FrameLayout xmlns:android=""

    android:elevation="@dimen/document_image_elevation" />

and then in onCreateView method

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);

    progress = view.findViewById(;

    imageView = view.findViewById(;
    imageView.setImageBitmap( bitmap );


    return view;

and then layoutImageView() code

private void layoutImageView(){

    float[] matrixv = new float[ 9 ];


    int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
    int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );



And the result is that image fits inside perfectly, keeping aspect ratio, and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.


It's important ImageView to have wrap_content and adjustViewBounds to true, then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,

/*An optional argument to supply a maximum height for this view. Only valid if
 * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
 * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
 * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
 * layout params to WRAP_CONTENT. */

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

Here's a Swift 4 UIView extension based on the answer from @Dima.

extension UIView {
   func snapshotImage() -> UIImage? {
       UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
       drawHierarchy(in: bounds, afterScreenUpdates: false)
       let image = UIGraphicsGetImageFromCurrentImageContext()
       return image

Scale the contents of a div by a percentage?

You can simply use the zoom property:

    zoom: 0.5;
    -moz-transform: scale(0.5);

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

Fit Image in ImageButton in Android

I want them to cover 75% of the button area.

Use android:padding="20dp" (adjust the padding as needed) to control how much the image takes up on the button.

but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?

Use a android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling.

All of these attributes can be set in code on each ImageButton at runtime. However, it is much easier to set and preview in xml in my opinion.

Also, do not use sp for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp dimensions will be larger than your intended if the user has a "large" text setting. Use dp instead, as it is not scaled by the user's text size preference.

Here's a snippet of what each button should look like:

        android:scaleType="fitCenter" />

Sample Button

How do I interpret precision and scale of a number in a database?

Precision of a number is the number of digits.

Scale of a number is the number of digits after the decimal point.

What is generally implied when setting precision and scale on field definition is that they represent maximum values.

Example, a decimal field defined with precision=5 and scale=2 would allow the following values:

  • 123.45 (p=5,s=2)
  • 12.34 (p=4,s=2)
  • 12345 (p=5,s=0)
  • 123.4 (p=4,s=1)
  • 0 (p=0,s=0)

The following values are not allowed or would cause a data loss:

  • 12.345 (p=5,s=3) => could be truncated into 12.35 (p=4,s=2)
  • 1234.56 (p=6,s=2) => could be truncated into 1234.6 (p=5,s=1)
  • 123.456 (p=6,s=3) => could be truncated into 123.46 (p=5,s=2)
  • 123450 (p=6,s=0) => out of range

Note that the range is generally defined by the precision: |value| < 10^p ...

simple Jquery hover enlarge

To create simple hover enlarge plugin, try this. (DEMO)


     <div id="content">
     <img src=" 11395-large.jpg" style="width:50%;" />


        $(function () {
          $('#content img').hover(function () {
          $(this).toggle(function () {

How to set the initial zoom/width for a webview

in Kotlin You can use,

webView.isScrollbarFadingEnabled = true

Adjusting the Xcode iPhone simulator scale and size

However iOS Simulator->HardWare->Device menu.

How to scale Docker containers in production

Deis automates scaling of Docker containers (among other things).

Deis (pronounced DAY-iss) is an open source PaaS that makes it easy to deploy and manage applications on your own servers. Deis builds upon Docker and CoreOS to provide a lightweight PaaS with a Heroku-inspired workflow.

Here is the developer workflow:

deis create myapp                      # create a new deis app called "myapp"
git push deis master                   # built with a buildpack or dockerfile
deis scale web=16 worker=4             # scale up docker containers

Deis automatically deploys your Docker containers across a CoreOS cluster and configures the Nginx routers to route requests to healthy Docker containers. If a host dies, containers are automatically restarted on another host in seconds. Just browse to the proxy URL or use deis open to hit your app.

Some other useful commands:

deis config:set DATABASE_URL=          # attach to a database w/ an envvar
deis run make test                     # run ephemeral containers for one-off tasks
deis logs                              # get aggregated logs for troubleshooting
deis rollback v23                      # rollback to a prior release

To see this in action, check out the terminal video at You can also learn about Deis concepts or jump right into deploying your own private PaaS.

Understanding `scale` in R

I thought I would contribute by providing a concrete example of the practical use of the scale function. Say you have 3 test scores (Math, Science, and English) that you want to compare. Maybe you may even want to generate a composite score based on each of the 3 tests for each observation. Your data could look as as thus:

student_id <- seq(1,10)
math <- c(502,600,412,358,495,512,410,625,573,522)
science <- c(95,99,80,82,75,85,80,95,89,86)
english <- c(25,22,18,15,20,28,15,30,27,18)
df <- data.frame(student_id,math,science,english)

Obviously it would not make sense to compare the means of these 3 scores as the scale of the scores are vastly different. By scaling them however, you have more comparable scoring units:

z <- scale(df[,2:4],center=TRUE,scale=TRUE)

You could then use these scaled results to create a composite score. For instance, average the values and assign a grade based on the percentiles of this average. Hope this helped!

Note: I borrowed this example from the book "R In Action". It's a great book! Would definitely recommend.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

As mentioned in the comments, there cannot be a continuous scale on variable of the factor type. You could change the factor to numeric as follows, just after you define the meltDF variable.


Then, execute the ggplot command

  ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y =   variable)) +
     scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

And you will have your chart.

Hope this helps

How to iterate for loop in reverse order in swift?

Swift 4 onwards

for i in stride(from: 5, to: 0, by: -1) {
//prints 5, 4, 3, 2, 1

for i in stride(from: 5, through: 0, by: -1) {
//prints 5, 4, 3, 2, 1, 0

Android Activity as a dialog

Some times you can get the Exception which is given below

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

So for resolving you can use simple solution

add theme of you activity in manifest as dialog for appCompact.


It can be helpful for somebody.

Single line sftp from terminal

sftp supports batch files.

From the man page:

-b batchfile

Batch mode reads a series of commands from an input batchfile instead of stdin.  
Since it lacks user interaction it should be used in conjunction with non-interactive
authentication.  A batchfile of `-' may be used to indicate standard input.  sftp 
will abort if any of the following commands fail: get, put, rename, ln, rm, mkdir, 
chdir, ls, lchdir, chmod, chown, chgrp, lpwd, df, symlink, and lmkdir.  Termination 
on error can be suppressed on a command by command basis by prefixing the command 
with a `-' character (for example, -rm /tmp/blah*).

how get yesterday and tomorrow datetime in c#

Today :


Tomorrow :


Yesterday :


How to delete a stash created with git stash create?

If you are 100% sure that you have just one stash or you want to delete all stashes (make a git stash list to be 107% sure), you can do a:

git stash clear

..and forget about them (it deletes all stashes).

Note: Added this answer for those who ended up here looking for a way to clear them all (like me).

How do I split a string in Rust?

There are three simple ways:

  1. By separator:

     s.split("separator")  |  s.split('/')  |  s.split(char::is_numeric)
  2. By whitespace:

  3. By newlines:

  4. By regex: (using regex crate)

     Regex::new(r"\s").unwrap().split("one two three")

The result of each kind is an iterator:

let text = "foo\r\nbar\n\nbaz\n";
let mut lines = text.lines();



Remove commas from the string using JavaScript

To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

Cannot serve WCF services in IIS on Windows 8

Seemed to be a no brainer; the WCF service should be enabled using Programs and Features -> Turn Windows features on or off in the Control Panel. Go to .NET Framework Advanced Services -> WCF Services and enable HTTP Activation as described in this blog post on mdsn.

From the command prompt (as admin), you can run:

C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45

If you get an error then use the below

C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation45

Binary Data in JSON String. Something better than Base64

Just to add the resource and complexity standpoint to the discussion. Since doing PUT/POST and PATCH for storing new resources and altering them, one should remember that the content transfer is an exact representation of the content that is stored and that is received by issuing a GET operation.

A multi-part message is often used as a savior but for simplicity reason and for more complex tasks, I prefer the idea of giving the content as a whole. It is self-explaining and it is simple.

And yes JSON is something crippling but in the end JSON itself is verbose. And the overhead of mapping to BASE64 is a way to small.

Using Multi-Part messages correctly one has to either dismantle the object to send, use a property path as the parameter name for automatic combination or will need to create another protocol/format to just express the payload.

Also liking the BSON approach, this is not that widely and easily supported as one would like it to be.

Basically, we just miss something here but embedding binary data as base64 is well established and way to go unless you really have identified the need to do the real binary transfer (which is hardly often the case).

mvn command is not recognized as an internal or external command

Try setting the path of maven first through command prompt.

setpath.bat Open the cmd from the base window of the batch file.

The rest maven commands can be used once path is set through cmd.

Setting "checked" for a checkbox with jQuery

This is probably the shortest and easiest solution:

$(".myCheckBox")[0].checked = true;


$(".myCheckBox")[0].checked = false;

Even shorter would be:

$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;

Here is a jsFiddle as well.

Select data from date range between two dates

You can also try using following fragments:

select  * from  Product_sales 
where  From_date  >= '2013-01-03' and game_date  <= '2013-01-09'

Redirect in Spring MVC

For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.

Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,

return "redirect:/index.html";  

should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.

Here is the source code of the method of RedirectView of Spring

protected void renderMergedOutputModel(  
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)  
throws IOException {  
  // Prepare target URL.  
  StringBuilder targetUrl = new StringBuilder();  
  if (this.contextRelative && getUrl().startsWith("/")) {  
    // Do not apply context path to relative URLs.  

  // ...  

  sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);  

Does a `+` in a URL scheme/host/path represent a space?

  • Percent encoding in the path section of a URL is expected to be decoded, but
  • any + characters in the path component is expected to be treated literally.

To be explicit: + is only a special character in the query component.

Finding all possible permutations of a given string in python

def perm(string):
   for j in range(0,len(string)):
           for i in perm(string[1:]):
           return [string];
   return res;

This is one way to generate permutations with recursion, you can understand the code easily by taking strings 'a','ab' & 'abc' as input.

You get all N! permutations with this, without duplicates.

Firefox setting to enable cross domain Ajax request

I used Fiddler as a proxy. Fiddler redirects localhost calls to a external server.

I configured Firefox to use manual proxy ( port 8888). Fiddler capture the calls and redirect them to another server, by using URL filters.

How can I hide/show a div when a button is clicked?

This can't be done with just HTML/CSS. You need to use javascript here. In jQuery it would be:

    e.preventDefault(); //to prevent standard click event

Apache 13 permission denied in user's home directory

im using CentOS 5.5 and for me it was SElinux messing with it, i forgot to check that out. you can temporary disable it by doing as root

echo 0 > /selinux/enforce

hope it help someone

How to get single value from this multi-dimensional PHP array

You can also use array_column(). It's available from PHP 5.5:

It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

print_r(array_column($myarray, 'email'));

What exactly are iterator, iterable, and iteration?

I don’t know if it helps anybody but I always like to visualize concepts in my head to better understand them. So as I have a little son I visualize iterable/iterator concept with bricks and white paper.

Suppose we are in the dark room and on the floor we have bricks for my son. Bricks of different size, color, does not matter now. Suppose we have 5 bricks like those. Those 5 bricks can be described as an object – let’s say bricks kit. We can do many things with this bricks kit – can take one and then take second and then third, can change places of bricks, put first brick above the second. We can do many sorts of things with those. Therefore this bricks kit is an iterable object or sequence as we can go through each brick and do something with it. We can only do it like my little son – we can play with one brick at a time. So again I imagine myself this bricks kit to be an iterable.

Now remember that we are in the dark room. Or almost dark. The thing is that we don’t clearly see those bricks, what color they are, what shape etc. So even if we want to do something with them – aka iterate through them – we don’t really know what and how because it is too dark.

What we can do is near to first brick – as element of a bricks kit – we can put a piece of white fluorescent paper in order for us to see where the first brick-element is. And each time we take a brick from a kit, we replace the white piece of paper to a next brick in order to be able to see that in the dark room. This white piece of paper is nothing more than an iterator. It is an object as well. But an object with what we can work and play with elements of our iterable object – bricks kit.

That by the way explains my early mistake when I tried the following in an IDLE and got a TypeError:

 >>> X = [1,2,3,4,5]
 >>> next(X)
 Traceback (most recent call last):
    File "<pyshell#19>", line 1, in <module>
 TypeError: 'list' object is not an iterator

List X here was our bricks kit but NOT a white piece of paper. I needed to find an iterator first:

>>> X = [1,2,3,4,5]
>>> bricks_kit = [1,2,3,4,5]
>>> white_piece_of_paper = iter(bricks_kit)
>>> next(white_piece_of_paper)
>>> next(white_piece_of_paper)

Don’t know if it helps, but it helped me. If someone could confirm/correct visualization of the concept, I would be grateful. It would help me to learn more.

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Easiest Way To install PDT

  1. Run eclipse
  2. Click on "Help", "Install New Software"
  3. “Choose all available sites”, in search box type "php"(takes a while to load)
  4. => “programming languages” => "PHP Development Tools", => PhP Development Tools (PDT) SDK Feature.
  5. Restart eclipse
  6. File new => other => php .
  7. Should be able to follow from their

How to disable <br> tags inside <div> by css?

or hide any br that follows the p tag, which are obviously not wanted

p + br {
    display: none;

How do I get extra data from intent on Android?


Set Data

String value = "Hello World!";
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
intent.putExtra("sample_name", value);

Get Data

String value;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    value = bundle.getString("sample_name");

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));


List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

How to install requests module in Python 3.4, instead of 2.7

On Windows with Python v3.6.5

py -m pip install requests

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

How to name variables on the fly?

It seems to me that you might be better off with a list rather than using orca1, orca2, etc, ... then it would be orca[1], orca[2], ...

Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.

orca <- list()
orca[1] <- "Hi"
orca[2] <- 59

Otherwise, assign is just what you want.

Beginner Python Practice?

You may be interested in Python interactive tutorial for begginers and advance users , it has many available practices together with interactive interface + advance development tricks for advance users.

How can I reverse a list in Python?



commands not found on zsh

For me just restarting my terminal seemed to fix the issue.

Perform an action in every sub-directory using Bash

find . -type d -print0 | xargs -0 -n 1 my_command

How to style a checkbox using CSS

This is simplest way and you can choose which checkboxes to give this style.


.check-box input {
  display: none;

.check-box span:before {
  content: ' ';
  width: 20px;
  height: 20px;
  display: inline-block;
  background: url("unchecked.png");

.check-box input:checked + span:before {
  background: url("checked.png");


<label class="check-box">
  <input type="checkbox">
  <span>Check box Text</span>

Set database timeout in Entity Framework

You can use this simple :

Spring get current ApplicationContext

Even better than having it with @Autowired is to let it be injected via constructor. Find some arguments pro constructor injection here

public class MyClass{
  private final ApplicationContext applicationContext;

  public MyClass(ApplicationContext applicationContext){
    this.applicationContext = applicationContext;

  //here will be your methods using the applicationcontext

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

What went wrong?

When you include jQuery the first time:

<script src=""></script>
<script src=""></script>

The second script plugs itself into jQuery, and "adds" $(...).datepicker.

But then you are including jQuery once again:

<script src=""></script>

It undoes the plugging in and therefore $(...).datepicker becomes undefined.

Although the first $(document).ready block appears before that, the anonymous callback function body is not executed until all scripts are loaded, and by then $(...) (window.$ to be precise) is referring to the most recently loaded jQuery.

You would not run into this if you called $('.dateinput').datepicker immediately rather than in $(document).ready callback, but then you'd need to make sure that the target element (with class dateinput) is already in the document before the script, and it's generally advised to use the ready callback.


If you want to use datepicker from jquery-ui, it would probably make most sense to include the jquery-ui script after bootstrap. jquery-ui 1.11.4 is compatible with jquery 1.6+ so it will work fine.

Alternatively (in particular if you are not using jquery-ui for anything else), you could try bootstrap-datepicker.

Visual Studio "Could not copy" .... during build

In my case it was Resharper Unit Tests runner (plus NUnit tests, never had such problem with MsTests). After killing the process, was able to rebuild process, without restarting OS or VS2013.

Other test runners, like xUnit can cause the same issue.

What helps then is to check if you can add a Dispose pattern, for example if you're adding a DbFixture and the database contacts isn't disposed properly. That will cause the assembly files being locked even if the tests completed.

Note that you can just add IDisposable interface to your DbFixture and let IntelliSense add the Dispose pattern. Then, dispose the related contained propertys and explicitly assign them to null.

That will help to end the tests in a clean way and unlock related locked files as soon as the tests ended.

Example (DBFixture is used by xUnit tests):

public class DbFixture: IDisposable
    private bool disposedValue;
    public ServiceProvider ServiceProvider { get; private set; }
    public DbFixture()
        // initializes ServiceProvider
    protected virtual void Dispose(bool disposing)
        if (!disposedValue)
            if (disposing)
                // dispose managed state (managed objects)
                ServiceProvider = null;

            // TODO: free unmanaged resources (unmanaged objects) and override finalizer
            // TODO: set large fields to null
            disposedValue = true;

    // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
    // ~DbFixture()
    // {
    //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
    //     Dispose(disposing: false);
    // }

    public void Dispose()
        // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
        Dispose(disposing: true);

The same pattern you need for the test class itself - it needs its own Dispose method (as shown for the DbFixture class above):

   public SQL_Tests(ITestOutputHelper output)
        this.Output = output;
        var fixture = new DbFixture(); // NOTE: MS Dependency injection framework didn't initialize when the fixture was a constructor param, hence it is here
        _serviceProvider = fixture.ServiceProvider;
    } // method

So it needs to dispose its local property _serviceProvider in its own Dispose method, because the test class constructor SQL_Tests instanciated it.

Click to call html

tl;dr What to do in modern (2018) times? Assume tel: is supported, use it and forget about anything else.

The tel: URI scheme RFC5431 (as well as sms: but also feed:, maps:, youtube: and others) is handled by protocol handlers (as mailto: and http: are).

They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto: protocol handler with same meaning and behaviour of tel: but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.

What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler() and related functions) simplifying also the check for their support through isProtocolHandlerRegistered() function.

There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).

In general what I suggest is:

  1. If you're running on a mobile device then you can safely assume tel: is supported (yes, it's not true for very old devices but IMO you can ignore them).
  2. If JS isn't active then do nothing.
  3. If you're running on desktop browsers then you can use one of the techniques in the linked post to determine if it's supported.
  4. If tel: isn't supported then change links to use callto: and repeat check desctibed in 3.
  5. If tel: and callto: aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href with javascript:void(0) and (if number isn't repeated in text span) putting, telephone number in title. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto: and tel:.

Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:

  1. If you're running on a mobile device then assume tel: is supported.
  2. If you're running on desktop then replace tel: with callto:. then drop tel: or leave it as is (assuming there are good chances Skype is installed).

What is the difference/usage of homebrew, macports or other package installation tools?

MacPorts is the way to go.

  1. Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.

  2. MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.

  3. MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.

  4. If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.

  5. MacPorts support groups.

    foo@macpro:~/ port select --summary
    Name        Selected      Options
    ====        ========      =======
    db          none          db46 none
    gcc         none          gcc42 llvm-gcc42 mp-gcc48 none
    llvm        none          mp-llvm-3.3 none
    mysql       mysql56       mysql56 none
    php         php55         php55 php56 none
    postgresql  postgresql94  postgresql93 postgresql94 none
    python      none          python24 python25-apple python26-apple python27 python27-apple none

    If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.

  6. Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I've come across the same issue after adding the following dependency:

implementation 'com.evernote:android-state:1.4.1'
annotationProcessor 'com.evernote:android-state-processor:1.4.1'

And the reason was that latest version of evernote uses dependencies to AndroidX, while I had support library version 27.1.1 in my project. So there was an option of upgrading support libraries to 28.0.0, as the other answers suggest, but that was a bit tricky for a large project with lots of custom views. So, I resolved the issue by downgrading evernote version to 1.3.1.

How to Batch Rename Files in a macOS Terminal?

To rename files, you can use the rename utility:

brew install rename

For example, to change a search string in all filenames in current directory:

rename -nvs searchword replaceword *

Remove the 'n' parameter to apply the changes.

More info: man rename

Get the first item from an iterable that matches a condition

The most efficient way in Python 3 are one of the following (using a similar example):

With "comprehension" style:

next(i for i in range(100000000) if i == 1000)

WARNING: The expression works also with Python 2, but in the example is used range that returns an iterable object in Python 3 instead of a list like Python 2 (if you want to construct an iterable in Python 2 use xrange instead).

Note that the expression avoid to construct a list in the comprehension expression next([i for ...]), that would cause to create a list with all the elements before filter the elements, and would cause to process the entire options, instead of stop the iteration once i == 1000.

With "functional" style:

next(filter(lambda i: i == 1000, range(100000000)))

WARNING: This doesn't work in Python 2, even replacing range with xrange due that filter create a list instead of a iterator (inefficient), and the next function only works with iterators.

Default value

As mentioned in other responses, you must add a extra-parameter to the function next if you want to avoid an exception raised when the condition is not fulfilled.

"functional" style:

next(filter(lambda i: i == 1000, range(100000000)), False)

"comprehension" style:

With this style you need to surround the comprehension expression with () to avoid a SyntaxError: Generator expression must be parenthesized if not sole argument:

next((i for i in range(100000000) if i == 1000), False)

How to get name of dataframe column in pyspark?

I found the answer is very very simple...

// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();

The variable "theNameOftheCol" is "colName"

Angular ui-grid dynamically calculate height of the grid

I use ui-grid - v3.0.0-rc.20 because a scrolling issue is fixed when you go full height of container. Use the ui.grid.autoResize module will dynamically auto resize the grid to fit your data. To calculate the height of your grid use the function below. The ui-if is optional to wait until your data is set before rendering.

angular.module('app',['ui.grid','ui.grid.autoResize']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {_x000D_
    $scope.gridData = {_x000D_
      rowHeight: 30, // set row height, this is default size_x000D_
    $scope.getTableHeight = function() {_x000D_
       var rowHeight = 30; // your row height_x000D_
       var headerHeight = 30; // your header height_x000D_
       return {_x000D_
          height: ($ * rowHeight + headerHeight) + "px"_x000D_
<div ui-if=">0" id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize ng-style="getTableHeight()"></div>

How to remove index.php from URLs?

You have to enable mod_rewrite in apache to make clean urls to work

if mod_rewrite is not in phpinfo you have to install it by

sudo a2enmod rewrite
sudo apache2ctl -l

You need to replace the occurrence of AllowOverride none to AllowOverride all ( in /etc/apache2/sites-enabled/000-default)

Restart Apache

sudo service apache2 restart

In Magento’s admin go to System > Configuration > Web > search engine Optimization and change “Use Web Server Rewrites” to Yes

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

The way I solved this issue was quite simple, I checked my chrome version and I had an older chromedriver in my PATH variable, so I downloaded the chromedriver version that matched my browser and replaced the old one in the PATH, so when the webdriver module looked for a chromedriver in my PATH, it would find the matching version

Writing an mp4 video using python opencv

There are some things to change in your code:

  1. Change the name of your output to 'output.mp4' (change to .mp4)
  2. I had the the same issues that people have in the comments, so I changed the fourcc to 0x7634706d: out = cv2.VideoWriter('output.mp4',0x7634706d , 20.0, (640,480))

Access to the path is denied

  1. Change the setting from built-in account to custom account and enter the other server's username and password.

  2. Keep the setting as integrated (instead of classic mode).

What are good examples of genetic algorithms/genetic programming solutions?

A coworker and I are working on a solution for loading freight onto trucks using the various criteria our company requires. I've been working on a Genetic Algorithm solution while he is using a Branch And Bound with aggressive pruning. We are still in the process of implementing this solution but so far, we have been getting good results.

Drawing Isometric game worlds

Either way gets the job done. I assume that by zigzag you mean something like this: (numbers are order of rendering)

..  ..  01  ..  ..
  ..  06  02  ..
..  11  07  03  ..
  16  12  08  04
21  17  13  09  05
  22  18  14  10
..  23  19  15  ..
  ..  24  20  ..
..  ..  25  ..  ..

And by diamond you mean:

..  ..  ..  ..  ..
  01  02  03  04
..  05  06  07  ..
  08  09  10  11
..  12  13  14  ..
  15  16  17  18
..  19  20  21  ..
  22  23  24  25
..  ..  ..  ..  ..

The first method needs more tiles rendered so that the full screen is drawn, but you can easily make a boundary check and skip any tiles fully off-screen. Both methods will require some number crunching to find out what is the location of tile 01. In the end, both methods are roughly equal in terms of math required for a certain level of efficiency.

How to filter a dictionary according to an arbitrary condition function?

dict((k, v) for k, v in points.items() if all(x < 5 for x in v))

You could choose to call .iteritems() instead of .items() if you're in Python 2 and points may have a lot of entries.

all(x < 5 for x in v) may be overkill if you know for sure each point will always be 2D only (in that case you might express the same constraint with an and) but it will work fine;-).

How do I export html table data as .csv file?

The following solution can do it.

$(function() {_x000D_
  $("button").on('click', function() {_x000D_
    var data = "";_x000D_
    var tableData = [];_x000D_
    var rows = $("table tr");_x000D_
    rows.each(function(index, row) {_x000D_
      var rowData = [];_x000D_
      $(row).find("th, td").each(function(index, column) {_x000D_
    data += tableData.join("\n");_x000D_
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
      type: "text/csv"_x000D_
    })) + '/>');_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
<script src=""></script>_x000D_
      <td>John Resig</td>_x000D_
      <td>The Write Less, Do More, JavaScript Library.</td>_x000D_
      <td>Jordan Walke</td>_x000D_
      <td>React makes it painless to create interactive UIs.</td>_x000D_
      <td>Yuxi You</td>_x000D_
      <td>The Progressive JavaScript Framework.</td>_x000D_
<div class="btn-group">_x000D_

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

How to export a Hive table into a CSV file?

I had a similar issue and this is how I was able to address it.

Step 1 - Loaded the data from hive table into another table as follows


Step 2 - Copied the blob from hive warehouse to the new location with appropriate extension

Start-AzureStorageBlobCopy -DestContext $destContext -SrcContainer "Source Container" -SrcBlob "hive/warehouse/TestHiveTableCSV/000000_0" -DestContainer "Destination Container" ` -DestBlob "CSV/TestHiveTable.csv"

Hope this helps!

Best Regards, Dattatrey Sindol (Datta)

How do you find the row count for all your tables in Postgres

Here is a much simpler way.

tables="$(echo '\dt' | psql -U "${PGUSER}" | tail -n +4 | head -n-2 | tr -d ' ' | cut -d '|' -f2)"
for table in $tables; do
printf "%s: %s\n" "$table" "$(echo "SELECT COUNT(*) FROM $table;" | psql -U "${PGUSER}" | tail -n +3 | head -n-2 | tr -d ' ')"

output should look like this

auth_group: 0
auth_group_permissions: 0
auth_permission: 36
auth_user: 2
auth_user_groups: 0
auth_user_user_permissions: 0
authtoken_token: 2
django_admin_log: 0
django_content_type: 9
django_migrations: 22
django_session: 0
mydata_table1: 9011
mydata_table2: 3499

you can update the psql -U "${PGUSER}" portion as needed to access your database

note that the head -n-2 syntax may not work in macOS, you could probably just use a different implementation there

Tested on psql (PostgreSQL) 11.2 under CentOS 7

if you want it sorted by table, then just wrap it with sort

for table in $tables; do
printf "%s: %s\n" "$table" "$(echo "SELECT COUNT(*) FROM $table;" | psql -U "${PGUSER}" | tail -n +3 | head -n-2 | tr -d ' ')"
done | sort -k 2,2nr


mydata_table1: 9011
mydata_table2: 3499
auth_permission: 36
django_migrations: 22
django_content_type: 9
authtoken_token: 2
auth_user: 2
auth_group: 0
auth_group_permissions: 0
auth_user_groups: 0
auth_user_user_permissions: 0
django_admin_log: 0
django_session: 0

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

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

$ ng eject

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

$ ng serve

you would have to do something like

$ npm run build & npm run start

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

linux shell script: split string, put them in an array then loop through them

while [ -n "${a}" ]
    echo ${a%%;*}

VBA to copy a file from one directory to another

One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):

  • My aim is to create a dynamic access dashboard, which requires that its linked tables be updated.
  • I use the copy methods described above to replace the existing linked CSVs with an updated version of them.
  • Running the above code manually from a module worked fine.
  • Running identical code from a form linked to the CSV data had runtime error 70 (Permission denied), even tho the first step of my code was to close that form (which should have unlocked the CSV file so that it could be overwritten).
  • I now believe that despite the form being closed, it keeps the outdated CSV file locked while it executes VBA associated with that form.

My solution will be to run the code (On timer event) from another hidden form that opens with the database.

how to run a command at terminal from java program?

You need to run it using bash executable like this:

Runtime.getRuntime().exec("/bin/bash -c your_command");

Update: As suggested by xav, it is advisable to use ProcessBuilder instead:

String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();

How to schedule a task to run when shutting down windows

I had to also enable "Specify maximum wait time for group policy scripts" and "Display instructions in shutdown scripts as they run" to make it work for me as I explain here.

Deploying Maven project throws invalid LOC header (bad signature)

From gsitgithub/find-currupt-jars.txt, the following command lists all the corrupted jar files in the repository:

find  /home/me/.m2/repository/ -name "*jar" | xargs -L 1 zip -T | grep error | grep invalid

You can delete the corrupted jar files, and recompile the project.

Example output:

warning [/cygdrive/J/repo/net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar]:  98304 extra bytes at beginning or within zipfile
  (attempting to process anyway)
file #1:  bad zipfile offset (local header sig):  98304
  (attempting to re-compensate)
zip error: Zip file invalid, could not spawn unzip, or wrong unzip (original files unmodified)

How do I switch between command and insert mode in Vim?

Looks like your Vim is launched in easy mode. See :help easy.

This happens when Vim is invoked with the -y argument or as evim, or maybe you have a :set insertmode somewhere in your .vimrc configuration. Find the source and disable it; temporarily this can be also done via Ctrl + O :set noim Enter.

Java - removing first character of a string

Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :

String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica

how to check which version of nltk, scikit learn installed?

import nltk is Python syntax, and as such won't work in a shell script.

To test the version of nltk and scikit_learn, you can write a Python script and run it. Such a script may look like

import nltk
import sklearn

print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))

# The nltk version is 3.0.0.
# The scikit-learn version is 0.15.2.

Note that not all Python packages are guaranteed to have a __version__ attribute, so for some others it may fail, but for nltk and scikit-learn at least it will work.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.


\chapter{Lorem ipsum}
\section{Dolor sit amet}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}

The output looks like

enter image description here

vertical align middle in <div>

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to #abc the following css:


Simple Demo

Original question demo updated

Simple Example:

.vertical-align-content {_x000D_
  /* Uncomment next line to get horizontal align also */_x000D_
  /* justify-content:center; */_x000D_
<div class="vertical-align-content">_x000D_

How to get HttpRequestMessage data

  System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
  reader.BaseStream.Position = 0;
  string requestFromPost = reader.ReadToEnd();

How to get a file directory path from file path?

If you care target files to be symbolic link, firstly you can check it and get the original file. The if clause below may help you.

if [ -h $file ]
 base=$(dirname $(readlink $file))
 base=$(dirname $file)

What are abstract classes and abstract methods?

abstract method do not have body.A well defined method can't be declared abstract.

A class which has abstract method must be declared as abstract.

Abstract class can't be instantiated.

How do I add button on each row in datatable?

var table =$('#example').DataTable( {
    data: yourdata ,
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "parent" },
        { data: "date" },

        {data: "id" , render : function ( data, type, row, meta ) {
              return type === 'display'  ?
                '<a href="<?php echo $delete_url;?>'+ data +'" ><i class="fe fe-delete"></i></a>' :

Why is Visual Studio 2010 not able to find/open PDB files?

I had the same problem. It turns out that, compiling a project I got from someone else, I haven't set the correct StartUp project (right click on the desired startup project in the solution explorer and pick "set as StartUp Project"). Maybe this will help, cheers.

Basic http file downloading and saving to disk in python?

Exotic Windows Solution

import subprocess"powershell Invoke-WebRequest {} -OutFile {}".format(your_url, filename), shell=True)

LINQ to SQL - How to select specific columns and return strongly typed list

Make a call to the DB searching with myid (Id of the row) and get back specific columns:

var columns = db.Notifications
                .Where(x => x.Id == myid)
                .Select(n => new { n.NotificationTitle, 
                                   n.NotificationOrder });

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.


You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

How to change the session timeout in PHP?

Put $_SESSION['login_time'] = time(); into the previous authentication page. And the snipped below in every other page where you want to check the session time-out.

if(time() - $_SESSION['login_time'] >= 1800){
    session_destroy(); // destroy session.
    header("Location: logout.php");
    die(); // See
    //redirect if the page is inactive for 30 minutes
else {        
   $_SESSION['login_time'] = time();
   // update 'login_time' to the last time a page containing this code was accessed.

Edit : This only works if you already used the tweaks in other posts, or disabled Garbage Collection, and want to manually check the session duration. Don't forget to add die() after a redirect, because some scripts/robots might ignore it. Also, directly destroying the session with session_destroy() instead of relying on a redirect for that might be a better option, again, in case of a malicious client or a robot.

Material effect on button with background color

I came to this post looking for a way to have a background color of my ListView Item, yet keep the ripple.

I simply added my color as a background and the selectableItemBackground as a foreground:

<style name="my_list_item">
    <item name="android:background">@color/white</item>
    <item name="android:foreground">?attr/selectableItemBackground</item>
    <item name="android:layout_height">@dimen/my_list_item_height</item>

and it works like a charm. I guess the same technique could be used for buttons as well. Good luck :)

Differentiate between function overloading and function overriding

Function overloading - functions with same name, but different number of arguments

Function overriding - concept of inheritance. Functions with same name and same number of arguments. Here the second function is said to have overridden the first

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

return url;

This will resolve your problem

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

What does random.sample() method in python do?

random.sample(population, k)

It is used for randomly sampling a sample of length 'k' from a population. returns a 'k' length list of unique elements chosen from the population sequence or set

it returns a new list and leaves the original population unchanged and the resulting list is in selection order so that all sub-slices will also be valid random samples

I am putting up an example in which I am splitting a dataset randomly. It is basically a function in which you pass x_train(population) as an argument and return indices of 60% of the data as D_test.

import random

def randomly_select_70_percent_of_data_from_1_to_length(x_train):
    return random.sample(range(0, len(x_train)), int(0.6*len(x_train)))

How to delete a record by id in Flask-SQLAlchemy

You can do this,



User.query.filter( == 123).delete()

Make sure to commit for delete() to take effect.

Reload child component when variables on parent component changes. Angular2

Use @Input to pass your data to child components and then use ngOnChanges ( to see if that @Input changed on the fly.

How can I manually set an Angular form field as invalid?

Here is an example that works:

MatchPassword(AC: FormControl) {
  let dataForm = AC.parent;
  if(!dataForm) return null;

  var newPasswordRepeat = dataForm.get('newPasswordRepeat');
  let password = dataForm.get('newPassword').value;
  let confirmPassword = newPasswordRepeat.value;

  if(password != confirmPassword) {
    /* for newPasswordRepeat from current field "newPassword" */
    dataForm.controls["newPasswordRepeat"].setErrors( {MatchPassword: true} );
    if( newPasswordRepeat == AC ) {
      /* for current field "newPasswordRepeat" */
      return {newPasswordRepeat: {MatchPassword: true} };
  } else {
    dataForm.controls["newPasswordRepeat"].setErrors( null );
  return null;

createForm() {
  this.dataForm ={
    password: [ "", Validators.required ],
    newPassword: [ "", [ Validators.required, Validators.minLength(6), this.MatchPassword] ],
    newPasswordRepeat: [ "", [Validators.required, this.MatchPassword] ]

MySQL the right syntax to use near '' at line 1 error

the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.

Either put it on one line or append on each line :o)

Sqlyog must be trimming white spaces on each line which explains why its working.


$qr2="INSERT INTO wp_bp_activity
 (this stuff)component,
     (is)      `type`,
    (a)        `action`,
  (problem)  content,

Create new project on Android, Error: Studio Unknown host ''

I also faced it and encorrected it like below successfully.

File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution

Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version

You may need to upgrade your gradle version.

PLS-00201 - identifier must be declared

When creating the TABLE under B2BOWNER, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert.

I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.

How can I add a string to the end of each line in Vim?


this will do the trick, and ensure leading spaces are ignored.

How to escape strings in SQL Server using PHP?

I have been using this as an alternative of mysql_real_escape_string():

function htmlsan($htmlsanitize){
    return $htmlsanitize = htmlspecialchars($htmlsanitize, ENT_QUOTES, 'UTF-8');
$data = "Whatever the value's is";
$data = stripslashes(htmlsan($data));

Converts scss to css

First of all, you have to install Ruby if it is not on your machine.

1.Open a terminal window. 2.Run the command which ruby.

If you see a path such as /usr/bin/ruby, Ruby is installed. If you don't see any response or get an error message, Ruby is not installed. To verify that you have a current version of Ruby, run the command ruby -v.

If ruby is not installed on your machine then

sudo apt-get install ruby2.0
sudo apt-get install ruby2.0-dev
sudo update-alternatives --install /usr/bin/gem gem /usr/bin/gem2.0 1 

After then install Sass gem by running this command

sudo gem install sass --no-user-install

Then copy or add any .sass file and go to that file path and then

sass --watch style.scss:style.css 

When ever it notices a change in the .scss file it will update your .css

This only works when your .scss is on your local machine. Try copying the code to a file and running it locally.

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

What kind of document library information do you want in the view? How do you want the user to filter the view?

In general the most powerful way of creating views in sharepoint is with the data view web part.

You will need Microsoft Office SharePoint Designer.

You can present different views of you folders using the data view filter and sorting controls.

You can use web part connections to filter a dataview. You can use any datasource linked to say a drop down to filter a dataview. How to tie a dropdown list to a gridview in Sharepoint 2007?

How do include paths work in Visual Studio?

This answer will be useful for those who use a non-standard IDE (i.e. Qt Creator).

There are at least two non-intrusive ways to pass additional include paths to Visual Studio's cl.exe via environment variables:

  • Set INCLUDE environment variable to ;-separated list of all include paths. It overrides all includes, inclusive standard library ones. Not recommended.
  • Set CL environment variable to the following value: /I C:\Lib\VulkanMemoryAllocator\src /I C:\Lib\gli /I C:\Lib\gli\external, where each argument of /I key is additional include path.

I successfully use the last one.

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

wget generally works in this way, but some sites may have problems and it may create too many unnecessary html files. In order to make this work easier and to prevent unnecessary file creation, I am sharing my getwebfolder script, which is the first linux script I wrote for myself. This script downloads all content of a web folder entered as parameter.

When you try to download an open web folder by wget which contains more then one file, wget downloads a file named index.html. This file contains a file list of the web folder. My script converts file names written in index.html file to web addresses and downloads them clearly with wget.

Tested at Ubuntu 18.04 and Kali Linux, It may work at other distros as well.

Usage :

  • extract getwebfolder file from zip file provided below

  • chmod +x getwebfolder (only for first time)

  • ./getwebfolder webfolder_URL

such as ./getwebfolder

Download Link

Details on blog

How to print an unsigned char in C?

This is because in this case the char type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u interprets the number as a large positive number:

212 = 0xD4

When it is sign-extended, FFs are pre-pended to your number, so it becomes

0xFFFFFFD4 = 4294967252

which is the number that gets printed.

Note that this behavior is specific to your implementation. According to C99 specification, all char types are promoted to (signed) int, because an int can represent all values of a char, signed or unsigned: If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

This results in passing an int to a format specifier %u, which expects an unsigned int.

To avoid undefined behavior in your program, add explicit type casts as follows:

unsigned char ch = (unsigned char)212;
printf("%u", (unsigned int)ch);

* In general, the standard leaves the signedness of char up to the implementation. See this question for more details.

How to build jars from IntelliJ properly?

My problem was this: I used Intellij IDEA (tried different versions) + Gradle. When I compiled the project and builded artifacf jar, as indicated in the above responses, I received an error - "no main manifest attrubute ..."

This solution worked for me (special thanks to Thilina Ashen Gamage (see above) for tip):

Excerpt - if you use external libraries and build a project through Project Settings - Artifacts - Add (+) - Jar - From modules with dependencies, then probably because of a program bug the META-INF folder with MANIFEST_MF file not including to jar. To avoid it create EMPTY jar file.

Project Settings - Artifacts - Add (+) - Jar - EMPTY JAR. META-INF folder will added to resources folder. Then select your main class. You will see following jar structure: note the presence of a folder META-INF Note the presence of a folder META-INF Then you can build your project and build artifacts. This solution worked for javaFX applications too.

Angular 2 Show and Hide an element

You should use the *ngIf Directive

<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.

export class AppComponent implements OnInit{

  public edited = false;
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
   }.bind(this), 3000);

Update: you are missing the reference to the outer scope when you are inside the Timeout callback.

so add the .bind(this) like I added Above

Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn

A : I would add edit as a property to the object I am iterating over.

<div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.

export class AppComponent implements OnInit{
  public listOfObjects = [
       name : 'obj - 1',
       edit : false
       name : 'obj - 2',
       edit : false
       name : 'obj - 2',
       edit : false
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
   }.bind(this), 3000);

How do you change the datatype of a column in SQL Server?

For changing data type

alter table table_name 
alter column column_name datatype [NULL|NOT NULL]

For changing Primary key

ALTER TABLE table_name  

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')'re trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

JavaScript get element by name

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);

connecting to mysql server on another PC in LAN

Connecting to any mysql database should be like this:

$mysql -h hostname -Pportnumber -u username -p (then enter)

Then it will ask for password. Note: Port number should be closer to -P or it will show error. Make sure you know what is your mysql port. Default is 3306 and is optional to specify the port in this case. If its anything else you need to mention port number with -P or else it will show error.

For example: $mysql -h -P3306 -u root -p (then enter)


Gubrish about product you using.


Note: If you are trying to connect a db at different location make sure you can ping to that server/computer.


It should return TTL with time you got back PONG. If it says destination unreachable then you cannot connect to remote mysql no matter what.

In such case contact your Network Administrator or Check your cable connection to your computer till the end of your target computer. Or check if you got LAN/WAN/MAN or internet/intranet/extranet working.

How can I create an MSI setup?

You can use "Visual studio installer project" and its free...

This is very easy to create installer and has GUI.(Most of the freeware MSI creation tool does not have a GUI part)

You will find many tutorials to create an installer easily on the internet

To install. just search Visual Studio Installer Project in your Visual Studio

Visual Studio-> Tools-> Extensions&updates ->search Visual Studio Installer Project. Download it and enjoy...

Delete all the queues from RabbitMQ?

In Rabbit version 3.7.10 you can run below command with root permission:

rabbitmqctl list_queues | awk '{ print $1 }' | xargs -L1 rabbitmqctl delete_queue

Number of days between past date and current date in Google spreadsheet

If you are using the two formulas at the same time, it will not work... Here is a simple spreadsheet with it working: If you are still getting problems I would need to know what type of erroneous result you are getting.

Today() returns a numeric integer value: Returns the current computer system date. The value is updated when your document recalculates. TODAY is a function without arguments.

How to get the scroll bar with CSS overflow on iOS

Edit following the comment left, kindly, by kritzikratzi:

[Starting] with ios 5beta a new property -webkit-overflow-scrolling: touch can be added which should result in the expected behaviour.

Some, but very little, further reading:

Original answer, left for posterity.

Unfortunately neither overflow: auto, or scroll, produces scrollbars on the iOS devices, apparently due to the screen-width that would be taken up such useful mechanisms.

Instead, as you've found, users are required to perform the two-finger swipe in order to scroll the overflow-ed content. The only reference, since I'm unable to find the manual for the phone itself, I could find is here: iPhone 101: Two-fingered scrolling.

The only work-around I can think of for this, is if you could possibly use some JavaScript, and maybe jQTouch, to create your own scroll-bars for overflow elements. Alternatively you could use @media queries to remove the overflow and show the content in full, as an iPhone user this gets my vote, if only for the sheer simplicity. For example:

<link rel="stylesheet" href="handheld.css" media="only screen and (max-device width:480px)" />

The preceding code comes from A List Apart, from the same article linked-to above (I'm not sure why they left of the type="text/css", but I assume there are reasons.

Accessing Google Account Id /username via Android

This Method to get Google Username:

 public String getUsername() {
    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("");
    List<String> possibleEmails = new LinkedList<String>();

    for (Account account : accounts) {
        // TODO: Check possibleEmail against an email regex or treat
        // as an email address only for certain account.type
        // values.

    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        String email = possibleEmails.get(0);
        String[] parts = email.split("@");
        if (parts.length > 0 && parts[0] != null)
            return parts[0];
            return null;
    } else
        return null;

simple this method call ....

And Get Google User in Gmail id::

 accounts = AccountManager.get(this).getAccounts();
    Log.e("", "Size: " + accounts.length);
    for (Account account : accounts) {

        String possibleEmail =;
        String type = account.type;

        if (type.equals("")) {
            strGmail = possibleEmail;

            Log.e("", "Emails: " + strGmail);

After add permission in manifest;

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

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

How do I add 24 hours to a unix timestamp in php?

$time = date("H:i", strtotime($today . " +5 hours +30 minutes"));
//+5 hours +30 minutes     Time Zone +5:30 (Asia/Kolkata)

Stopping a thread after a certain amount of time

If you want to use a class:

from datetime import datetime,timedelta

class MyThread(): 

    def __init__(self, name, timeLimit):        = name
        self.timeLimit = timeLimit
    def run(self): 
        # get the start time
        startTime =
        while True:
           # stop if the time limit is reached :

mt = MyThread('aThread',timedelta(microseconds=20000))

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?


This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations.


It’s very fast to retrieve single values from database. Execute Scalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013"

Convert Date To String

Use name Space

using System.Globalization;


string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");

printf() prints whole array

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

How do I create a local database inside of Microsoft SQL Server 2014?

Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link

Youtube video about entire process.
Writeup with pictures about installing SQL Server

How to select a local server:

When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:

1) Make sure you have Server Type: Database

2) Make sure you have Authentication: Windows Authentication (no username & password)

3) For the server name field look to the right and select the drop down arrow, click 'browse for more'

4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14

How do I create a local database inside of Microsoft SQL Server 2014?

1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)

2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!

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

Almost everybody answered this. My version of printing any rails exception into logs would be:

rescue => e
    puts "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
    Rails.logger.error "Exception Occurred #{e}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"

What is a void pointer in C++?

Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:

General Syntax:

void* pointer_variable;

void *pVoid; // pVoid is a void pointer

A void pointer can point to objects of any data type:

int nValue;
float fValue;

struct Something
    int nValue;
    float fValue;

Something sValue;

void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid

However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.

int nValue = 5;
void *pVoid = &nValue;

// can not dereference pVoid because it is a void pointer

int *pInt = static_cast<int*>(pVoid); // cast from void* to int*

cout << *pInt << endl; // can dereference pInt

Source: link

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Download data url file

Your problem essentially boils down to "not all browsers will support this".

You could try a workaround and serve the unzipped files from a Flash object, but then you'd lose the JS-only purity (anyway, I'm not sure whether you currently can "drag files into browser" without some sort of Flash workaround - is that a HTML5 feature maybe?)

Express-js can't GET my static files, why?

I am using Bootstrap CSS, JS and Fonts in my application. I created a folder called asset in root directory of the app and place all these folder inside it. Then in server file added following line:


This line enables me to load the files that are in the asset directory from the /asset path prefix like: http://localhost:3000/asset/css/bootstrap.min.css.

Now in the views I can simply include CSS and JS like below:

<link href="/asset/css/bootstrap.min.css" rel="stylesheet">

Is it possible to modify a string of char in C?

It seems like your question has been answered but now you might wonder why char *a = "String" is stored in read-only memory. Well, it is actually left undefined by the c99 standard but most compilers choose to it this way for instances like:

printf("Hello, World\n");

c99 standard(pdf) [page 130, section 6.7.8]:

The declaration:

char s[] = "abc", t[3] = "abc";

defines "plain" char array objects s and t whose elements are initialized with character string literals. This declaration is identical to char

s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

How do you access the value of an SQL count () query in a Java program

It's similar to above but you can try like

public Integer count(String tableName) throws CrateException {
        String query = String.format("Select count(*) as size from %s", tableName);
        try (Statement s = connection.createStatement()) {
            try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
                Preconditions.checkArgument(, "Result set is empty");
                return resultSet.getInt("size");
        } catch (SQLException e) {
            throw new CrateException(e);

How to start Activity in adapter?

callback from adapter to activity can be done using registering listener in form of interface: Make an interface:

      public MyInterface{
         public void  yourmethod(//incase needs parameters );

In Adapter Let's Say MyAdapter:

    public MyAdapter extends BaseAdapter{
       private MyInterface listener;

    MyAdapter(Context context){
        try {
            this. listener = (( MyInterface ) context);
              } catch (ClassCastException e) {
               throw new ClassCastException("Activity must implement MyInterface");

//do this where u need to fire listener l

          try {
                listener . yourmethod ();
            } catch (ClassCastException exception) {
               // do something

      In Activity Implement your method:

         MyActivity extends AppCompatActivity implements MyInterface{

                //do whatever you want

Python Accessing Nested JSON Data

Places is a list and not a dictionary. This line below should therefore not work:

print data['places']['latitude']

You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:

print data['places'][0]['post code']

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');

You can try it here:

Convert a dataframe to a vector (by rows)

You can try this to get your combination:

as.numeric(rbind(test$x, test$y))

which will return:

26, 34, 21, 29, 20, 28

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

In my particular case, I was trying to store a Base64 encoded file into a table BLOB field, using Mybatis.

So in my xml I had:

<insert id="save..." parameterType="...DTO">
    <selectKey keyProperty="id" resultType="long" order="BEFORE">
        SELECT SEQ.nextVal FROM DUAL
    insert into MYTABLE(
    ) values (
        #{id, jdbcType=VARCHAR},
        #{tcPdf, jdbcType=BLOB},

and in my DTO:

String getPdf(){
    return pdf;

That makes to Mybatis threat as if were a String char sequence and try to store it as a Varchar. So my solution was the following:

In my DTO:

Byte[] getPdf(){
    return pdf.getBytes();

And worked.

I hope this could help anybody.

Fade Effect on Link Hover?

I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.


.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: color 0.3s linear;
   -webkit-transition: color 0.3s linear;
   -moz-transition: color 0.3s linear;

.fancy-link:hover {
   color: #F44336;


<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the above code!

Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.


.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: all 0.3s linear;
   -webkit-transition: all 0.3s linear;
   -moz-transition: all 0.3s linear;

.fancy-link:hover {
   color: #F44336;
   padding-left: 10px;


<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the "all" example!

How to easily duplicate a Windows Form in Visual Studio?

1.Add a new folder to your project

2.Copy the form into that

3.Change the name in properties as well as change the file name

4.Check each form for their class name (they shouldn't be same)

Selenium WebDriver findElement(By.xpath()) not working for me

element = findElement(By.xpath("//*[@test-id='test-username']");
element = findElement(By.xpath("//input[@test-id='test-username']");

(*) - any tagname

How to generate a GUID in Oracle?

Creating a 350 characters GUID:

dbms_random.STRING ('a', 350) - returning string in mixed case alpha characters

dbms_random.STRING ('x', 350) - returning string in uppercase alpha-numeric characters

How do I create batch file to rename large number of files in a folder?

you can do this easily without manual editing or using fancy text editors. Here's a vbscript.

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    If objFS.GetExtensionName(strFile) = "jpg" Then    
        strFileName = strFile.Name
        If InStr(strFileName,"Vacation2010") > 0 Then           
            strNewFileName = Replace(strFileName,"Vacation2010","December")
            strFile.Name = strNewFileName
        End If 
    End If  

save as myscript.vbs and

C:\test> cscript //nologo myscript.vbs 

getting error while updating Composer

The good solution for this error please run this command

composer install --ignore-platform-reqs

JUnit: how to avoid "no runnable methods" in test utils classes

My specific case has the following scenario. Our tests

public class VenueResourceContainerTest extends BaseTixContainerTest

all extend


and JUnit was trying to run BaseTixContainerTest. Poor BaseTixContainerTest was just trying to setup the container, setup the client, order some pizza and relax... man.

As mentioned previously, you can annotate the class with


But that caused JUnit to report that test as skipped (as opposed to completely ignored).

Tests run: 4, Failures: 0, Errors: 0, Skipped: 1

That kind of irritated me.

So I made BaseTixContainerTest abstract, and now JUnit truly ignores it.

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

XSS prevention in JSP/Servlet web application

The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.

On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.

Empty set literal?

By all means, please use set() to create an empty set.

But, if you want to impress people, tell them that you can create an empty set using literals and * with Python >= 3.5 (see PEP 448) by doing:

>>> s = {*()}  # or {*{}} or {*[]}
>>> print(s)

this is basically a more condensed way of doing {_ for _ in ()}, but, don't do this.

Excel VBA Run-time Error '32809' - Trying to Understand it

It seems that 32809 is a general error message. After struggling for some time, I found that I had not clicked on the "Enable Macros" security button at the below the workbook ribbon. Once I did this, everything worked fine.

How do I get today's date in C# in mm/dd/yyyy format?


I think this is what you are looking for

Understanding the Gemfile.lock file

You can find more about it in the bundler website (emphasis added below for your convenience):

After developing your application for a while, check in the application together with the Gemfile and Gemfile.lock snapshot. Now, your repository has a record of the exact versions of all of the gems that you used the last time you know for sure that the application worked...

This is important: the Gemfile.lock makes your application a single package of both your own code and the third-party code it ran the last time you know for sure that everything worked. Specifying exact versions of the third-party code you depend on in your Gemfile would not provide the same guarantee, because gems usually declare a range of versions for their dependencies.

How to compare 2 files fast using .NET?

It's getting even faster if you don't read in small 8 byte chunks but put a loop around, reading a larger chunk. I reduced the average comparison time to 1/4.

    public static bool FilesContentsAreEqual(FileInfo fileInfo1, FileInfo fileInfo2)
        bool result;

        if (fileInfo1.Length != fileInfo2.Length)
            result = false;
            using (var file1 = fileInfo1.OpenRead())
                using (var file2 = fileInfo2.OpenRead())
                    result = StreamsContentsAreEqual(file1, file2);

        return result;

    private static bool StreamsContentsAreEqual(Stream stream1, Stream stream2)
        const int bufferSize = 1024 * sizeof(Int64);
        var buffer1 = new byte[bufferSize];
        var buffer2 = new byte[bufferSize];

        while (true)
            int count1 = stream1.Read(buffer1, 0, bufferSize);
            int count2 = stream2.Read(buffer2, 0, bufferSize);

            if (count1 != count2)
                return false;

            if (count1 == 0)
                return true;

            int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
            for (int i = 0; i < iterations; i++)
                if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
                    return false;

Package signatures do not match the previously installed version

Go to android studio -> AVD manager -> Select your AVD and wipe user data

No need to re-install the entire AVD.

Return multiple values in JavaScript?

It is possible to return a string with many values and variables using the template literals `${}`


var newCodes = function() {  
    var dCodes =;
    var dCodes2 =;
    return `${dCodes}, ${dCodes2}`;

It's short and simple.

How to do SQL Like % in Linq?

I'm assuming you're using Linq-to-SQL* (see note below). If so, use string.Contains, string.StartsWith, and string.EndsWith to generate SQL that use the SQL LIKE operator.

from o in dc.Organization
join oh in dc.OrganizationsHierarchy on o.Id equals oh.OrganizationsId
where oh.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }


from o in dc.Organization
where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

Note: * = if you are using the ADO.Net Entity Framework (EF / L2E) in .net 3.5, be aware that it will not do the same translation as Linq-to-SQL. Although L2S does a proper translation, L2E v1 (3.5) will translate into a t-sql expression that will force a full table scan on the table you're querying unless there is another better discriminator in your where clause or join filters.
Update: This is fixed in EF/L2E v4 (.net 4.0), so it will generate a SQL LIKE just like L2S does.

How to check null objects in jQuery

Check the jQuery FAQ...

You can use the length property of the jQuery collection returned by your selector:

if ( $('#myDiv').length ){}

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

Please remove all jar files of Http from libs folder and add below dependencies in gradle file :

compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4.3'


How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();

this should help you.

How to specify more spaces for the delimiter using cut?

I like to use the tr -s command for this

 ps aux | tr -s [:blank:] | cut -d' ' -f3

This squeezes all white spaces down to 1 space. This way telling cut to use a space as a delimiter is honored as expected.

How can I enable Assembly binding logging?

If you sometimes run different versions of your application, make sure you delete 'Bla' from the application bin directory if the version running doesn't need it.

Convert String[] to comma separated string in java

You could also simplify it using the Guava library:

String[] name = {"amit", "rahul", "surya"};
String str = "'" + Joiner.on(",").skipNulls().join(name)
    .replace(",", "','") + "'";

Docker: Multiple Dockerfiles in project

In newer versions(>=1.8.0) of docker, you can do this

docker build -f Dockerfile.db .
docker build -f Dockerfile.web .

A big save.

EDIT: update versions per raksja's comment

EDIT: comment from @vsevolod: it's possible to get syntax highlighting in VS code by giving files .Dockerfile extension(instead of name) e.g. Prod.Dockerfile, Test.Dockerfile etc.

How to force IE to reload javascript?

Paolo's general idea (i.e. effectively changing some part of the request uri) is your best bet. However, I'd suggest using a more static value such as a version number that you update when you have changed your script file so that you can still get the performance gains of caching.

So either something like this:

<script src="/my/js/file.js?version=2.1.3" ></script>

or maybe

<script src="/my/js/file.2.1.3.js" ></script>

I prefer the first option because it means you can maintain the one file instead of having to constantly rename it (which for example maintains consistent version history in your source control). Of course either one (as I've described them) would involve updating your include statements each time, so you may want to come up with a dynamic way of doing it, such as replacing a fixed value with a dynamic one every time you deploy (using Ant or whatever).

Sorting by date & time in descending order?

SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9

"DESC" stands for descending but you need ascending order ("ASC").

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

Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

This means that the following code is completely safe:

if(p != null && p.getAge() > 10)

Also, a || b never evaluates b if a evaluates to true.

How to remove carriage return and newline from a variable in shell script

use this command on your script file after copying it to Linux/Unix

perl -pi -e 's/\r//' scriptfilename

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");; // FileOutputStream 

input file appears to be a text format dump. Please use psql

If you have a full DB dump:

PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql

If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers. You can then use this:

cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin

On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump is incompatible with pg_restore. With some additional keys, however, it is. WTF?

How do I create documentation with Pydoc?

As RocketDonkey suggested, your module itself needs to have some docstrings.

For example, in myModule/

The mod module

You'd also want to generate documentation for each file in myModule/*.py using

pydoc myModule.thefilename

to make sure the generated files match the ones that are referenced from the main module documentation file.

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

Dump a mysql database to a plaintext (CSV) backup from the command line

You can use below script to get the output to csv files. One file per table with headers.

for tn in `mysql --batch --skip-page --skip-column-name --raw -uuser -ppassword -e"show tables from mydb"`
mysql -uuser -ppassword mydb -B -e "select * from \`$tn\`;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > $tn.csv

user is your user name, password is the password if you don't want to keep typing the password for each table and mydb is the database name.

Explanation of the script: The first expression in sed, will replace the tabs with "," so you have fields enclosed in double quotes and separated by commas. The second one insert double quote in the beginning and the third one insert double quote at the end. And the final one takes care of the \n.

How to keep environment variables when using sudo

The trick is to add environment variables to sudoers file via sudo visudo command and add these lines:

Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"

taken from ArchLinux wiki.

For Ubuntu 14, you need to specify in separate lines as it returns the errors for multi-variable lines:

Defaults  env_keep += "http_proxy"
Defaults  env_keep += "https_proxy"
Defaults  env_keep += "HTTP_PROXY"
Defaults  env_keep += "HTTPS_PROXY"

install / uninstall APKs programmatically (PackageManager vs Intents)


Your APK needs to be signed by system as correctly pointed out earlier. One way to achieve that is building the AOSP image yourself and adding the source code into the build.


Once installed as a system app, you can use the package manager methods to install and uninstall an APK as following:


public boolean install(final String apkPath, final Context context) {
    Log.d(TAG, "Installing apk at " + apkPath);
    try {
        final Uri apkUri = Uri.fromFile(new File(apkPath));
        final String installerPackageName = "MyInstaller";
        context.getPackageManager().installPackage(apkUri, installObserver, PackageManager.INSTALL_REPLACE_EXISTING, installerPackageName);
        return true;
    } catch (Exception e) {
        return false;


public boolean uninstall(final String packageName, final Context context) {
    Log.d(TAG, "Uninstalling package " + packageName);
    try {
        context.getPackageManager().deletePackage(packageName, deleteObserver, PackageManager.DELETE_ALL_USERS);
        return true;
    } catch (Exception e) {
        return false;

To have a callback once your APK is installed/uninstalled you can use this:

 * Callback after a package was installed be it success or failure.
private class InstallObserver implements IPackageInstallObserver {

    public void packageInstalled(String packageName, int returnCode) throws RemoteException {

        if (packageName != null) {
            Log.d(TAG, "Successfully installed package " + packageName);
            callback.onAppInstalled(true, packageName);
        } else {
            Log.e(TAG, "Failed to install package.");
            callback.onAppInstalled(false, null);

    public IBinder asBinder() {
        return null;

 * Callback after a package was deleted be it success or failure.
private class DeleteObserver implements IPackageDeleteObserver {

    public void packageDeleted(String packageName, int returnCode) throws RemoteException {
        if (packageName != null) {
            Log.d(TAG, "Successfully uninstalled package " + packageName);
            callback.onAppUninstalled(true, packageName);
        } else {
            Log.e(TAG, "Failed to uninstall package.");
            callback.onAppUninstalled(false, null);

    public IBinder asBinder() {
        return null;

 * Callback to give the flow back to the calling class.
public interface InstallerCallback {
    void onAppInstalled(final boolean success, final String packageName);
    void onAppUninstalled(final boolean success, final String packageName);

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is:


2 : if you are interested in loading the class , execute its static blocks and also want to access its its non static part , then you need an instance and then you need:


removing bold styling from part of a header

<h1 style="font-weight: normal;"></h1>

try this?

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

Python: Converting string into decimal number

A2 = [float(x.strip('"')) for x in A1] works, @Jake , but there are unnecessary 0s

What should a Multipart HTTP request with multiple files look like?

EDIT: I am maintaining a similar, but more in-depth answer at:

To see exactly what is happening, use nc -l and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html


nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

Content-Disposition: form-data; name="text"

text default
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>


Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

How to store Node.js deployment settings/configuration files?

I use a package.json for my packages and a config.js for my configuration, which looks like:

var config = {};

config.twitter = {};
config.redis = {};
config.web = {};

config.default_stuff =  ['red','green','blue','apple','yellow','orange','politics'];
config.twitter.user_name = process.env.TWITTER_USER || 'username';
config.twitter.password=  process.env.TWITTER_PASSWORD || 'password';
config.redis.uri = process.env.DUOSTACK_DB_REDIS; = 'hostname';
config.redis.port = 6379;
config.web.port = process.env.WEB_PORT || 9980;

module.exports = config;

I load the config from my project:

var config = require('./config');

and then I can access my things from config.db_host, config.db_port, etc... This lets me either use hardcoded parameters, or parameters stored in environmental variables if I don't want to store passwords in source control.

I also generate a package.json and insert a dependencies section:

"dependencies": {
  "cradle": "0.5.5",
  "jade": "0.10.4",
  "redis": "0.5.11",
  "": "0.6.16",
  "twitter-node": "0.0.2",
  "express": "2.2.0"

When I clone the project to my local machine, I run npm install to install the packages. More info on that here.

The project is stored in GitHub, with remotes added for my production server.

WPF Datagrid set selected row

I have changed the code of serge_gubenko and it works better

for (int i = 0; i < dataGrid.Items.Count; i++)
    string txt = searchTxt.Text;
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
    TextBlock cellContent = dataGrid.Columns[1].GetCellContent(row) as TextBlock;
    if (cellContent != null && cellContent.Text.ToLower().Equals(txt.ToLower()))
        object item = dataGrid.Items[i];
        dataGrid.SelectedItem = item;
        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

How to apply multiple transforms in CSS?

You can also apply multiple transforms using an extra layer of markup e.g.:

<h3 class="rotated-heading">
    <span class="scaled-up">Hey!</span>
<style type="text/css">
    transform: rotate(10deg);

    transform: scale(1.5);

This can be really useful when animating elements with transforms using Javascript.

What are the file limits in Git (number and size)?

There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.

There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.

%find . -type f | wc -l
%time git add .
git add .  6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status  0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G     .
%cd .git
%du -sh .
7.9G    .

Delete all rows in a table based on another table

This will delete all rows in Table1 that match the criteria:

DELETE Table1 
FROM Table2 
WHERE Table1.JoinColumn = Table2.JoinColumn And Table1.SomeStuff = 'SomeStuff'

HTML.HiddenFor value set

Necroing this question because I recently ran into the problem myself, when trying to add a related property to an existing entity. I just ended up making a nice extension method:

    public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, TProperty value)
        string expressionText = ExpressionHelper.GetExpressionText(expression);
        string propertyName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);

        return htmlHelper.Hidden(propertyName, value);

Use like so:

@Html.HiddenFor(m => m.RELATED_ID, Related.Id)

Note that this has a similar signature to the built-in HiddenFor, but uses generic typing, so if Value is of type System.Object, you'll actually be invoking the one built into the framework. Not sure why you'd be editing a property of type System.Object in your views though...

Commit empty folder structure (with git)

Recursively create .gitkeep files

find . -type d -empty -not -path "./.git/*" -exec touch {}/.gitkeep \;

What is the best way to generate a unique and short file name in Java

I use the timestamp


new File( simpleDateFormat.format( new Date() ) );

And have the simpleDateFormat initialized to something like as:

new SimpleDateFormat("File-ddMMyy-hhmmss.SSS.txt");


What about

new File(String.format("%s.%s", sdf.format( new Date() ),

Unless the number of files created in the same second is too high.

If that's the case and the name doesn't matters

 new File( "file."+count++ );


How to get N rows starting from row M from sorted table in T-SQL

This thread is quite old, but currently you can do this: much cleaner imho

FROM Sales.SalesOrderDetail
ORDER BY SalesOrderDetailID


Swift: Display HTML data in a label or textView

Add this extension to convert your html code to a regular string:

    extension String {

        var html2AttributedString: NSAttributedString? {
                let data = dataUsingEncoding(NSUTF8StringEncoding)
            else { return nil }
            do {
                return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
            } catch let error as NSError {
                return  nil
        var html2String: String {
            return html2AttributedString?.string ?? ""

And then you show your String inside an UITextView Or UILabel

textView.text = yourString.html2String or

label.text = yourString.html2String

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

"Unmappable character for encoding UTF-8" error

The Java compiler assumes that your input is UTF-8 encoded, either because you specified it to be or because it's your platform default encoding.

However, the data in your .java files is not actually encoded in UTF-8. The problem is probably the ¬ character. Make sure your editor (or IDE) of choice actually safes its file in UTF-8 encoding.

SQL Server using wildcard within IN

I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with ORs will do it.

select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or 
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%') 

Get individual query parameters from Uri

You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

This is how i solve my problem

let parameters = [
            "station_id" :        "1000",
            "title":      "Murat Akdeniz",
            "body":        "xxxxxx"]

let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1)

        multipartFormData: { MultipartFormData in
        //    multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")

            for (key, value) in parameters {
                MultipartFormData.append( String.Encoding.utf8)!, withName: key)

        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")

    }, to: "") { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in

        case .failure(let encodingError): break


When should I use Async Controllers in ASP.NET MVC?

My experience is that today a lot of developers use async/await as a default for controllers.

My suggestion would be, use it only when you know it will help you.

The reason is, as Stephen Cleary and others already mentioned, it can introduce performance issues, rather than resolving them, and it will help you only in a specific scenario:

  • High-traffic controllers
  • Scalable backend

Best way to alphanumeric check in JavaScript

You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.

function validateCode(){
    var TCode = document.getElementById('TCode').value;
    if( /[^a-zA-Z0-9]/.test( TCode ) ) {
       alert('Input is not alphanumeric');
       return false;
    return true;     

If there's at least one match of a non alpha numeric, it will return false.

Defining a `required` field in Bootstrap

To make a field required, use required or required="true"

I think required="required" has been deprecated in version 3 of bootstrap.

Can I have multiple Xcode versions installed?

Note that if you use the xcodebuild command line tool, then the last version of Xcode installed will become the default version. (A symbolic link is installed in /usr/bin.) To use the xcodebuild for the other versions of Xcode you'll need to use the version in the (xcode_install_directory)/usr/bin directory.

note To switch between different versions of the Xcode command-line tools, use the xcode-select tool mentioned by other commenters.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

If you knew the Class of ImplementationType you could create an instance of it. So what you are trying to do is not possible.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

Or you can do it like as well:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

How to fix: /usr/lib/ version `GLIBCXX_3.4.15' not found

I fixed this issue by installing: sudo apt-get install libstdc++6

In my case, I ran into this issue after installing MongoDB 3.0.1

mongo: /usr/lib/x86_64-linux-gnu/ version `GLIBCXX_3.4.18' not found (required by mongo)

Escape single quote character for use in an SQLite query

Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.

String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");

 String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";

this works for me in c# and java

How to make an array of arrays in Java

there is the class I mentioned in the comment we had with Sean Patrick Floyd : I did it with a peculiar use which needs WeakReference, but you can change it by any object with ease.

Hoping this can help someone someday :)

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

 * @author leBenj
public class Array2DWeakRefsBuffered<T>
    private final WeakReference<T>[][] _array;
    private final Queue<T> _buffer;

    private final int _width;

    private final int _height;

    private final int _bufferSize;

    @SuppressWarnings( "unchecked" )
    public Array2DWeakRefsBuffered( int w , int h , int bufferSize )
        _width = w;
        _height = h;
        _bufferSize = bufferSize;
        _array = new WeakReference[_width][_height];
        _buffer = new LinkedList<T>();

     * Tests the existence of the encapsulated object
     * /!\ This DOES NOT ensure that the object will be available on next call !
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     */public boolean exists( int x , int y ) throws IndexOutOfBoundsException
        if( x >= _width || x < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        if( y >= _height || y < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        if( _array[x][y] != null )
            T elem = _array[x][y].get();
            if( elem != null )
            return true;
        return false;

     * Gets the encapsulated object
     * @param x
     * @param y
     * @return
     * @throws IndexOutOfBoundsException
     * @throws NoSuchElementException
    public T get( int x , int y ) throws IndexOutOfBoundsException , NoSuchElementException
        T retour = null;
        if( x >= _width || x < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ x = " + x + "]" );
        if( y >= _height || y < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (get) : [ y = " + y + "]" );
        if( _array[x][y] != null )
            retour = _array[x][y].get();
            if( retour == null )
            throw new NoSuchElementException( "Dereferenced WeakReference element at [ " + x + " ; " + y + "]" );
            throw new NoSuchElementException( "No WeakReference element at [ " + x + " ; " + y + "]" );
        return retour;

     * Add/replace an object
     * @param o
     * @param x
     * @param y
     * @throws IndexOutOfBoundsException
    public void set( T o , int x , int y ) throws IndexOutOfBoundsException
        if( x >= _width || x < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ x = " + x + "]" );
        if( y >= _height || y < 0 )
            throw new IndexOutOfBoundsException( "Index out of bounds (set) : [ y = " + y + "]" );
        _array[x][y] = new WeakReference<T>( o );

        // store local "visible" references : avoids deletion, works in FIFO mode
        _buffer.add( o );
        if(_buffer.size() > _bufferSize)


Example of how to use it :

// a 5x5 array, with at most 10 elements "bufferized" -> the last 10 elements will not be taken by GC process
Array2DWeakRefsBuffered<Image> myArray = new Array2DWeakRefsBuffered<Image>(5,5,10);
Image img = myArray.set(anImage,0,0);
    System.out.println("Image at 3,3 is still in memory");

Html/PHP - Form - Input as array

If is ok for you to index the array you can do this:

    <input type="text" class="form-control" placeholder="Titel" name="levels[0][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[0][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[1][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[1][build_time]">

    <input type="text" class="form-control" placeholder="Titel" name="levels[2][level]">
    <input type="text" class="form-control" placeholder="Titel" name="levels[2][build_time]">

... to achieve that:

[levels] => Array ( 
  [0] => Array ( 
    [level] => 1 
    [build_time] => 2 
  [1] => Array ( 
    [level] => 234 
   [build_time] => 456 
  [2] => Array ( 
    [level] => 111
    [build_time] => 222 

But if you remove one pair of inputs (dynamically, I suppose) from the middle of the form then you'll get holes in your array, unless you update the input names...

Is there any ASCII character for <br>?

The answer is amp#13; — change "amp" to the ampersand sign and go.

Gradle - Could not find or load main class

If you're using Spring Boot, this might be the issue:

Basically, the output directories changed in Gradle 4.0, so if you have them hardcoded the execution will fail.

The solution is to replace:

bootRun {
   dependsOn pathingJar
   doFirst {
      classpath = files("$buildDir/classes/main", "$buildDir/resources/main", pathingJar.archivePath)


bootRun {
   dependsOn pathingJar
   doFirst {
      classpath = files(sourceSets.main.output.files, pathingJar.archivePath)

diff current working copy of a file with another branch's committed copy

To see local changes compare to your current branch

git diff .

To see local changed compare to any other existing branch

git diff <branch-name> .

To see changes of a particular file

git diff <branch-name> -- <file-path>

Make sure you run git fetch at the beginning.

Scroll / Jump to id without jQuery

Oxi's answer is just wrong.¹

What you want is:

var container = document.body,
element = document.getElementById('ElementID');
container.scrollTop = element.offsetTop;

Working example:

(function (){
  var i = 20, l = 20, html = '';
  while (i--){
    html += '<div id="DIV' +(l-i)+ '">DIV ' +(l-i)+ '</div>';
    html += '<a onclick="document.body.scrollTop=document.getElementById(\'DIV' +i+ '\').offsetTop">';
    html += '[ Scroll to #DIV' +i+ ' ]</a>';
    html += '<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />';
  document.write( html );

¹ I haven't got enough reputation to comment on his answer

How do I make entire div a link?

Wrapping a <a> around won't work (unless you set the <div> to display:inline-block; or display:block; to the <a>) because the div is s a block-level element and the <a> is not.

<a href="" style="display:block;">

<a href="">
   <div style="display:inline-block;">

<a href="">
   </span >

<a href="">

But maybe you should skip the <div> and choose a <span> instead, or just the plain <a>. And if you really want to make the div clickable, you could attach a javascript redirect with a onclick handler, somethign like:

document.getElementById("myId").setAttribute('onclick', 'location.href = "url"'); 

but I would recommend against that.

Get element of JS object with an index

If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.

For example, using an array, you could do this:

var myobj = [{"A":["B"]}, {"B": ["C"]}];
var firstItem = myobj[0];

Then, you can use myobj[0] to get the first object in the array.

Or, depending upon what you're trying to do:

var myobj = [{key: "A", val:["B"]}, {key: "B",  val:["C"]}];
var firstKey = myobj[0].key;   // "A"
var firstValue = myobj[0].val; // "["B"]

Center a H1 tag inside a DIV

You can add line-height:51px to #AlertDiv h1 if you know it's only ever going to be one line. Also add text-align:center to #AlertDiv.

#AlertDiv {

#AlertDiv h1 {

The demo below also uses negative margins to keep the #AlertDiv centered on both axis, even when the window is resized.


Listing all the folders subfolders and files in a directory using php

function listFolderFiles($dir){
    $ffs = scandir($dir);

    unset($ffs[array_search('.', $ffs, true)]);
    unset($ffs[array_search('..', $ffs, true)]);

    // prevent empty ordered elements
    if (count($ffs) < 1)

    echo '<ol>';
    foreach($ffs as $ff){
        echo '<li>'.$ff;
        if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
        echo '</li>';
    echo '</ol>';

listFolderFiles('Main Dir');

Unrecognized escape sequence for path string containing backslashes

Try this:

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

The problem is that in a string, a \ is an escape character. By using the @ sign you tell the compiler to ignore the escape characters.

You can also get by with escaping the \:

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";