Programs & Examples On #Many to one

Defines a single-valued association to another entity class that has many-to-one multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, the non-owning OneToMany entity side must used the mappedBy element to specify the relationship field or property of the entity that is the owner of the relationship.

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

In JPA 2.0 if you want to delete an address if you removed it from a User entity you can add orphanRemoval=true (instead of CascadeType.REMOVE) to your @OneToMany.

More explanation between orphanRemoval=true and CascadeType.REMOVE is here.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

Difference between one-to-many and many-to-one relationship

one-to-many has parent class contains n number of childrens so it is a collection mapping.

many-to-one has n number of childrens contains one parent so it is a object mapping

JPA: unidirectional many-to-one and cascading delete

@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)

Given annotation worked for me. Can have a try

For Example :-

     public class Parent{
            @Id
            @GeneratedValue(strategy=GenerationType.AUTO)
            @Column(name="cct_id")
            private Integer cct_id;
            @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
            @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
            private List<Child> childs;
        }
            public class Child{
            @ManyToOne(fetch=FetchType.EAGER)
            @JoinColumn(name="cct_id")
            private Parent parent;
    }

Google Recaptcha v3 example demo

I am assuming you have site key and secret in place. Follow this step.

In your HTML file, add the script.

 <script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>

Also, do use jQuery for easy event handling.

Here is the simple form.

 <form id="comment_form" action="form.php" method="post" >
      <input type="email" name="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
    </form>

You need to initialize the Google recaptcha and listen for the ready event. Here is how to do that.

     <script>
       // when form is submit
    $('#comment_form').submit(function() {
        // we stoped it
        event.preventDefault();
        var email = $('#email').val();
        var comment = $("#comment").val();
        // needs for recaptacha ready
        grecaptcha.ready(function() {
            // do request for recaptcha token
            // response is promise with passed token
            grecaptcha.execute('put your site key here', {action: 'create_comment'}).then(function(token) {
                // add token to form
                $('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
                $.post("form.php",{email: email, comment: comment, token: token}, function(result) {
                        console.log(result);
                        if(result.success) {
                                alert('Thanks for posting comment.')
                        } else {
                                alert('You are spammer ! Get the @$%K out.')
                        }
                });
            });
        });
  });
  </script>

Here is the sample PHP file. You can use Servlet or Node or any backend language in place of it.

<?php

        $email;$comment;$captcha;
        if(isset($_POST['email'])){
          $email=$_POST['email'];
        }if(isset($_POST['comment'])){
          $comment=$_POST['comment'];
        }if(isset($_POST['token'])){
          $captcha=$_POST['token'];
          }
        if(!$captcha){
          echo '<h2>Please check the the captcha form.</h2>';
          exit;
        }
        $secretKey = "put your secret key here";
        $ip = $_SERVER['REMOTE_ADDR'];

        // post request to server

        $url =  'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
        $response = file_get_contents($url);
        $responseKeys = json_decode($response,true);
        header('Content-type: application/json');
        if($responseKeys["success"]) {
                echo json_encode(array('success' => 'true'));
        } else {
                echo json_encode(array('success' => 'false'));
        }
?>

Here is the tutorial link: https://codeforgeek.com/2019/02/google-recaptcha-v3-tutorial/

Hope it helps.

How to remove gem from Ruby on Rails application?

If you're using Rails 3+, remove the gem from the Gemfile and run bundle install.

If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install should do the trick.

Prevent redirect after form is submitted

$('#registerform').submit(function(e) {
   e.preventDefault();
   $.ajax({
        type: 'POST',
        url: 'submit.php',
        data: $(this).serialize(),
        beforeSend: //do something
        complete: //do something
        success: //do something for example if the request response is success play your animation...
   });

})

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

How do I convert from int to Long in Java?

If you already have the int typed as an Integer you can do this:

Integer y = 1;
long x = y.longValue();

Trim a string based on the string length

tl;dr

You seem to be asking for an ellipsis () character in the last place, when truncating. Here is a one-liner to manipulate your input string.

String input = "abcdefghijkl";
String output = ( input.length () > 10 ) ? input.substring ( 0 , 10 - 1 ).concat ( "…" ) : input;

See this code run live at IdeOne.com.

abcdefghi…

Ternary operator

We can make a one-liner by using the ternary operator.

String input = "abcdefghijkl" ;

String output = 
    ( input.length() > 10 )          // If too long…
    ?                                
    input     
    .substring( 0 , 10 - 1 )         // Take just the first part, adjusting by 1 to replace that last character with an ellipsis.
    .concat( "…" )                   // Add the ellipsis character.
    :                                // Or, if not too long…
    input                            // Just return original string.
;

See this code run live at IdeOne.com.

abcdefghi…

Java streams

The Java Streams facility makes this interesting, as of Java 9 and later. Interesting, but maybe not the best approach.

We use code points rather than char values. The char type is legacy, and is limited to the a subset of all possible Unicode characters.

String input = "abcdefghijkl" ;
int limit = 10 ;
String output =
        input
                .codePoints()
                .limit( limit )
                .collect(                                    // Collect the results of processing each code point.
                        StringBuilder::new,                  // Supplier<R> supplier
                        StringBuilder::appendCodePoint,      // ObjIntConsumer<R> accumulator
                        StringBuilder::append                // BiConsumer<R,?R> combiner
                )
                .toString()
        ;

If we had excess characters truncated, replace the last character with an ellipsis.

if ( input.length () > limit )
{
    output = output.substring ( 0 , output.length () - 1 ) + "…";
}

If only I could think of a way to put together the stream line with the "if over limit, do ellipsis" part.

Need to remove href values when printing in Chrome

I encountered a similar problem only with a nested img in my anchor:

<a href="some/link">
   <img src="some/src">
</a>

When I applied

@media print {
   a[href]:after {
      content: none !important;
   }
}

I lost my img and the entire anchor width for some reason, so instead I used:

@media print {
   a[href]:after {
      visibility: hidden;
   }
}

which worked perfectly.

Bonus tip: inspect print preview

Using Caps Lock as Esc in Mac OS X

It is now much easier to map the Caps Lock key to Esc with macOS Sierra.

  1. Open System Preferences ? Keyboard.

  2. Click the Modifier Keys button in the bottom right-hand corner.

  3. Click the drop down box next to the hardware key that you’d like to remap, and select Escape.

  4. Click OK and close System Preferences.

enter image description here

https://9to5mac.com/2016/10/25/remap-escape-key-action-macbook-pro-macos-sierra-10-12-1-modifier-keys/

Way to create multiline comments in Bash?

I tried the chosen answer, but found when I ran a shell script having it, the whole thing was getting printed to screen (similar to how jupyter notebooks print out everything in '''xx''' quotes) and there was an error message at end. It wasn't doing anything, but: scary. Then I realised while editing it that single-quotes can span multiple lines. So.. lets just assign the block to a variable.

x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"

ls -l
date

'

How can I run another application within a panel of my C# program?

I notice that all the prior answers use older Win32 User library functions to accomplish this. I think this will work in most cases, but will work less reliably over time.

Now, not having done this, I can't tell you how well it will work, but I do know that a current Windows technology might be a better solution: the Desktop Windows Manager API.

DWM is the same technology that lets you see live thumbnail previews of apps using the taskbar and task switcher UI. I believe it is closely related to Remote Terminal services.

I think that a probable problem that might happen when you force an app to be a child of a parent window that is not the desktop window is that some application developers will make assumptions about the device context (DC), pointer (mouse) position, screen widths, etc., which may cause erratic or problematic behavior when it is "embedded" in the main window.

I suspect that you can largely eliminate these problems by relying on DWM to help you manage the translations necessary to have an application's windows reliably be presented and interacted with inside another application's container window.

The documentation assumes C++ programming, but I found one person who has produced what he claims is an open source C# wrapper library: https://bytes.com/topic/c-sharp/answers/823547-desktop-window-manager-wrapper. The post is old, and the source is not on a big repository like GitHub, bitbucket, or sourceforge, so I don't know how current it is.

How to fill OpenCV image with one solid color?

Use numpy.full. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.

import cv2
import numpy as np

gray_img = np.full((100, 100, 3), 127, np.uint8)

blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)

full_layer = np.full((100, 100), 255, np.uint8)

# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer

cv2.imshow('2x2_grid', np.vstack([
    np.hstack([gray_img, blue_img]), 
    np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')

How to shutdown my Jenkins safely?

If you would like to stop jenkins and all its services on the server using Linux console (e.g. Ubuntu), run:

service jenkins start/stop/restart

This is useful when you need to make an image/volume snapshot and you want all services to stop writing to the disk/volume.

Explode PHP string by new line

try

explode(chr(10), $_POST['skuList']);

Big-O summary for Java Collections Framework implementations?

The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).

List implementations:

                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)

Set implementations:

                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)

Map implementations:

                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)

Queue implementations:

                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

The bottom of the javadoc for the java.util package contains some good links:

Show spinner GIF during an $http request in AngularJS?

If you are using ngResource, the $resolved attribute of an object is useful for loaders:

For a resource as follows:

var User = $resource('/user/:id', {id:'@id'});
var user = User.get({id: 1})

You can link a loader to the $resolved attribute of the resource object:

<div ng-hide="user.$resolved">Loading ...</div>

Can I update a component's props in React.js?

PROPS

A React component should use props to store information that can be changed, but can only be changed by a different component.

STATE

A React component should use state to store information that the component itself can change.

A good example is already provided by Valéry.

Angular bootstrap datepicker date format does not format ng-model value

Although similar answers have been posted I'd like to contribute what seemed to be the easiest and cleanest fix to me. Assuming you are using the AngularUI datepicker and your initial value for the ng-Model does not get formatted simply adding the following directive to your project will fix the issue:

angular.module('yourAppName')
.directive('datepickerPopup', function (){
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, controller) {
      //remove the default formatter from the input directive to prevent conflict
      controller.$formatters.shift();
  }
}
});

I found this solution in the Github AngularUI issues and therefore all credit goes to the people over there.

Android: How to detect double-tap?

Solution by bughi & Jayant Arora for copypast:

public abstract class DoubleClickListener implements View.OnClickListener {
private int position;
private Timer timer;

private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds

long lastClickTime = 0;

public DoubleClickListener (int position) {
    this.position = position;
}

@Override
public void onClick(View v) {
    long clickTime = System.currentTimeMillis();
    if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
        if (timer != null) {
            timer.cancel(); //Cancels Running Tasks or Waiting Tasks.
            timer.purge();  //Frees Memory by erasing cancelled Tasks.
        }
        onDoubleClick(v, position);
    } else {
        final Handler handler = new Handler();
        final Runnable mRunnable = () -> {
            onSingleClick(v, position);
        };
        TimerTask timertask = new TimerTask() {
            @Override
            public void run() {
                handler.post(mRunnable);
            }
        };
        timer = new Timer();
        timer.schedule(timertask, DOUBLE_CLICK_TIME_DELTA);

    }
    lastClickTime = clickTime;
}

public abstract void onSingleClick(View v, int position);
public abstract void onDoubleClick(View v, int position);}

How do I drop a MongoDB database from the command line?

You don't need heredocs or eval, mongo itself can act as an interpreter.

#!/usr/bin/env mongo
var db = new Mongo().getDB("someDatabase");
db.dropDatabase();

Make the file executable and run it.

Spring Data JPA findOne() change to Optional how to use this?

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Now, findOne() has neither the same signature nor the same behavior.
Previously, it was defined in the CrudRepository interface as:

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is the one defined in the QueryByExampleExecutor interface as:

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want that as a replacement.

In fact, the method with the same behavior is still there in the new API, but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional, which is not so bad to prevent NullPointerException.

So, the actual method to invoke is now Optional<T> findById(ID id).

How to use that?
Learning Optional usage. Here's important information about its specification:

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).


Some hints on how to use Optional with Optional<T> findById(ID id).

Generally, as you look for an entity by id, you want to return it or make a particular processing if that is not retrieved.

Here are three classical usage examples.

  1. Suppose that if the entity is found you want to get it otherwise you want to get a default value.

You could write :

Foo foo = repository.findById(id)
                    .orElse(new Foo());

or get a null default value if it makes sense (same behavior as before the API change) :

Foo foo = repository.findById(id)
                    .orElse(null);
  1. Suppose that if the entity is found you want to return it, else you want to throw an exception.

You could write :

return repository.findById(id)
        .orElseThrow(() -> new EntityNotFoundException(id));
  1. Suppose you want to apply a different processing according to if the entity is found or not (without necessarily throwing an exception).

You could write :

Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()) {
    Foo foo = fooOptional.get();
    // processing with foo ...
} else {
    // alternative processing....
}

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

Limiting the number of characters in a JTextField

Since the introduction of the DocumentFilter in Java 1.4, the need to override Document has been lessoned.

DocumentFilter provides the means for filtering content been passed to the Document before it actually reaches it.

These allows the field to continue to maintain what ever document it needs, while providing the means to filter the input from the user.

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class LimitTextField {

    public static void main(String[] args) {
        new LimitTextField();
    }

    public LimitTextField() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JTextField pfPassword = new JTextField(20);
                ((AbstractDocument)pfPassword.getDocument()).setDocumentFilter(new LimitDocumentFilter(15));

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(pfPassword);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class LimitDocumentFilter extends DocumentFilter {

        private int limit;

        public LimitDocumentFilter(int limit) {
            if (limit <= 0) {
                throw new IllegalArgumentException("Limit can not be <= 0");
            }
            this.limit = limit;
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            int currentLength = fb.getDocument().getLength();
            int overLimit = (currentLength + text.length()) - limit - length;
            if (overLimit > 0) {
                text = text.substring(0, text.length() - overLimit);
            }
            if (text.length() > 0) {
                super.replace(fb, offset, length, text, attrs); 
            }
        }

    }

}

What is the advantage of using REST instead of non-REST HTTP?

  • Give every “resource” an ID
  • Link things together
  • Use standard methods
  • Resources with multiple representations
  • Communicate statelessly

It is possible to do everything just with POST and GET? Yes, is it the best approach? No, why? because we have standards methods. If you think again, it would be possible to do everything using just GET.. so why should we even bother do use POST? Because of the standards!

For example, today thinking about a MVC model, you can limit your application to respond just to specific kinds of verbs like POST, GET, PUT and DELETE. Even if under the hood everything is emulated to POST and GET, don't make sense to have different verbs for different actions?

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

Generating 8-character only UUIDs

Not a UUID, but this works for me:

UUID.randomUUID().toString().replace("-","").substring(0,8)

Effectively use async/await with ASP.NET Web API

It is correct, but perhaps not useful.

As there is nothing to wait on – no calls to blocking APIs which could operate asynchronously – then you are setting up structures to track asynchronous operation (which has overhead) but then not making use of that capability.

For example, if the service layer was performing DB operations with Entity Framework which supports asynchronous calls:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    using (db = myDBContext.Get()) {
      var list = await db.Countries.Where(condition).ToListAsync();

       return list;
    }
}

You would allow the worker thread to do something else while the db was queried (and thus able to process another request).

Await tends to be something that needs to go all the way down: it is very hard to retro-fit into an existing system.

insert multiple rows into DB2 database

UPDATE - Even less wordy version

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5'),
       ('val1', 'val2', 'val3', 'val4', 'val5')

The following also works for DB2 and is slightly less wordy

INSERT INTO tableName (col1, col2, col3, col4, col5) 
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5') UNION ALL
VALUES ('val1', 'val2', 'val3', 'val4', 'val5')

PHP substring extraction. Get the string before the first '/' or the whole string

One-line version of the accepted answer:

$out=explode("/", $mystring, 2)[0];

Should work in php 5.4+

Java : Sort integer array without using Arrays.sort()

This will surely help you.

int n[] = {4,6,9,1,7};

    for(int i=n.length;i>=0;i--){
        for(int j=0;j<n.length-1;j++){
            if(n[j] > n[j+1]){
                swapNumbers(j,j+1,n);
            }
        }

    }
    printNumbers(n);
}
private static void swapNumbers(int i, int j, int[] array) {

    int temp;
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

private static void printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {
        System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
}

How can I add the sqlite3 module to Python?

if you have error in Sqlite built in python you can use Conda to solve this conflict

conda install sqlite

Change the color of a bullet in a html list?

Wrap the text within the list item with a span (or some other element) and apply the bullet color to the list item and the text color to the span.

PHP Fatal error: Class 'PDO' not found

If you have upgraded your PHP version, make sure that the old PHP version configuration in your .htaccess has been deleted. For more info, check this https://www.hostgator.com/help/article/php-configuration-plugin

Open S3 object as a string with Boto3

read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called models.py,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

UITextField border color

If you use a TextField with rounded corners use this code:

    self.TextField.layer.cornerRadius=8.0f;
    self.TextField.layer.masksToBounds=YES;
    self.TextField.layer.borderColor=[[UIColor redColor]CGColor];
    self.TextField.layer.borderWidth= 1.0f;

To remove the border:

self.TextField.layer.masksToBounds=NO;
self.TextField.layer.borderColor=[[UIColor clearColor]CGColor];

How can I dismiss the on screen keyboard?

To dismiss the keyboard (1.7.8+hotfix.2 and above) just call the method below:

FocusScope.of(context).unfocus();

Once the FocusScope.of(context).unfocus() method already check if there is focus before dismiss the keyboard it's not needed to check it. But in case you need it just call another context method: FocusScope.of(context).hasPrimaryFocus

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

On the model set $incrementing to false

public $incrementing = false;

This will stop it from thinking it is an auto increment field.

Laravel Docs - Eloquent - Defining Models

Blade if(isset) is not working Laravel

You can use the ternary operator easily:

{{ $usersType ? $usersType : '' }}

curl_init() function not working

On newer versions of PHP on Windows, like PHP 7.x, the corresponding configuration lines suggested on previous answers here, have changed. You need to uncomment (remove the ; at the beginning of the line) the following line:

extension_dir = "ext"
extension=curl

Convert multidimensional array into single array

I had come across the same requirement to flatter multidimensional array into single dimensional array than search value using text in key. here is my code

$data = '{
    "json_data": [{
            "downtime": true,
            "pfix": {
                "max": 100,
                "threshold": 880
            },
            "ints": {
                "int": [{
                    "rle": "pri",
                    "device": "laptop",
                    "int": "Ether3",
                    "ip": "127.0.0.3"
                }],
                "eth": {
                    "lan": 57
                }
            }
        },
        {
            "downtime": false,
            "lsi": "987654",
            "pfix": {
                "min": 10000,
                "threshold": 890
            },
            "mana": {
                "mode": "NONE"
            },
            "ints": {
                "int": [{
                    "rle": "sre",
                    "device": "desk",
                    "int": "Ten",
                    "ip": "1.1.1.1",
                    "UF": true
                }],
                "ethernet": {
                    "lan": 2
                }
            }
        }
    ]
}
';

$data = json_decode($data,true);


$stack = &$data;
$separator = '.';
$toc = array();

while ($stack) {
    list($key, $value) = each($stack);
    unset($stack[$key]);
    if (is_array($value)) {
        $build = array($key => ''); # numbering without a title.
        foreach ($value as $subKey => $node)
            $build[$key . $separator . $subKey] = $node;
        $stack = $build + $stack;
        continue;
    }
    if(!is_numeric($key)){
        $toc[$key] = $value;
    }
}


echo '<pre/>';
print_r($toc);


My output:

Array
(
    [json_data] => 
    [json_data.0] => 
    [json_data.0.downtime] => 1
    [json_data.0.pfix] => 
    [json_data.0.pfix.max] => 100
    [json_data.0.pfix.threshold] => 880
    [json_data.0.ints] => 
    [json_data.0.ints.int] => 
    [json_data.0.ints.int.0] => 
    [json_data.0.ints.int.0.rle] => pri
    [json_data.0.ints.int.0.device] => laptop
    [json_data.0.ints.int.0.int] => Ether3
    [json_data.0.ints.int.0.ip] => 127.0.0.3
    [json_data.0.ints.eth] => 
    [json_data.0.ints.eth.lan] => 57
    [json_data.1] => 
    [json_data.1.downtime] => 
    [json_data.1.lsi] => 987654
    [json_data.1.pfix] => 
    [json_data.1.pfix.min] => 10000
    [json_data.1.pfix.threshold] => 890
    [json_data.1.mana] => 
    [json_data.1.mana.mode] => NONE
    [json_data.1.ints] => 
    [json_data.1.ints.int] => 
    [json_data.1.ints.int.0] => 
    [json_data.1.ints.int.0.rle] => sre
    [json_data.1.ints.int.0.device] => desk
    [json_data.1.ints.int.0.int] => Ten
    [json_data.1.ints.int.0.ip] => 1.1.1.1
    [json_data.1.ints.int.0.UF] => 1
    [json_data.1.ints.ethernet] => 
    [json_data.1.ints.ethernet.lan] => 2
)

java comparator, how to sort by integer?

If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

For example, a Comparator<Dog> to sort Dog instances descending by age could be created with the following:

Comparable.comparingToInt(Dog::getDogAge).reversed();

The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

How can I sort a dictionary by key?

Guys you are making things complicated ... it's really simple

from pprint import pprint
Dict={'B':1,'A':2,'C':3}
pprint(Dict)

The output is:

{'A':2,'B':1,'C':3}

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

I am a fan of keeping logic out of the template as much as possible. I would suggest creating a helper function that returns the data that you care about to the template. For instance:

getItemsForDisplay():String[] {
 return [].concat.apply([],this.groups.map(group => group.items));
};

<tr *ngFor="let item of getItemsForDisplay()"><td>{{item}}</td></tr>

This will let you keep your presentation free of special logic. This also lets you use your datasource "directly".

Generate unique random numbers between 1 and 100

This solution uses the hash which is much more performant O(1) than checking if the resides in the array. It has extra safe checks too. Hope it helps.

function uniqueArray(minRange, maxRange, arrayLength) {
  var arrayLength = (arrayLength) ? arrayLength : 10
  var minRange = (minRange !== undefined) ? minRange : 1
  var maxRange = (maxRange !== undefined) ? maxRange : 100
  var numberOfItemsInArray = 0
  var hash = {}
  var array = []

  if ( arrayLength > (maxRange - minRange) ) throw new Error('Cannot generate unique array: Array length too high')

  while(numberOfItemsInArray < arrayLength){
    // var randomNumber = Math.floor(Math.random() * (maxRange - minRange + 1) + minRange)
    // following line used for performance benefits
    var randomNumber = (Math.random() * (maxRange - minRange + 1) + minRange) << 0

    if (!hash[randomNumber]) {
      hash[randomNumber] = true
      array.push(randomNumber)
      numberOfItemsInArray++
    }
  }
  return array
}
document.write(uniqueArray(1, 100, 8))

First Heroku deploy failed `error code=H10`

I was deploying python Django framework when I got this error because I forget to put my app name web: gunicorn plaindjango.wsgi:application --log-file - instead of plaindjango

Web Service vs WCF Service

Basic and primary difference is, ASP.NET web service is designed to exchange SOAP messages over HTTP only while WCF Service can exchange message using any format (SOAP is default) over any transport protocol i.e. HTTP, TCP, MSMQ or NamedPipes etc.

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I had the same issue. adding

<mvc:annotation-driven />
<mvc:default-servlet-handler />

to the spring-xml solved it

Generate PDF from Swagger API documentation

Handy way: Using Browser Printing/Preview

  1. Hide editor pane
  2. Print Preview (I used firefox, others also fine)
  3. Change its page setup and print to pdf

enter image description here

how to destroy an object in java?

Here is the code:

public static void main(String argso[]) {
int big_array[] = new int[100000];

// Do some computations with big_array and get a result. 
int result = compute(big_array);

// We no longer need big_array. It will get garbage collected when there
// are no more references to it. Since big_array is a local variable,
// it refers to the array until this method returns. But this method
// doesn't return. So we've got to explicitly get rid of the reference
// ourselves, so the garbage collector knows it can reclaim the array. 
big_array = null;

// Loop forever, handling the user's input
for(;;) handle_input(result);
}

Amazon Linux: apt-get: command not found

I faced the same issue regarding apt-get: command not found here are the steps how I resolved it on ubuntu xenial

  • Search the appropriate version of apt from here (apt_1.4_amd64.deb for ubuntu xenial)

  • Download the apt.deb

    wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb

  • Install the apt.deb package

    sudo dpkg -i apt_1.4_amd64.deb

Now we can easily run

sudo apt-get install htop

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

How do I parse a string with a decimal point to a double?

Here is a solution that handles any number string that many include commas and periods. This solution is particular for money amounts so only the tenths and hundredths place are expected. Anything more is treated as a whole number.

First remove anything that is not a number, comma, period, or negative sign.

string stringAmount = Regex.Replace(originalString, @"[^0-9\.\-,]", "");

Then we split up the number into the whole number and decimal number.

string[] decimalParsed = Regex.Split(stringAmount, @"(?:\.|,)(?=\d{2}$)");

(This Regex expression selects a comma or period that is two numbers from the end of the string.)

Now we take the whole number and strip it of any commas and periods.

string wholeAmount = decimalParsed[0].Replace(",", "").Replace(".", "");

if (wholeAmount.IsNullOrEmpty())
        wholeAmount = "0";

Now we handle the decimal part, if any.

string decimalAmount = "00";

if (decimalParsed.Length == 2)
    {
        decimalAmount = decimalParsed[1];
    }

Finally we can put the whole and decimal together and parse the Double.

double amount = $"{wholeAmount}.{decimalAmount}".ToDouble();

This will handle 200,00, 1 000,00 , 1,000 , 1.000,33 , 2,000.000,78 etc.

How to type a new line character in SQL Server Management Studio

You can't.

Use a "new query" window instead, and do a manual update:

UPDATE mytable
SET textvalue = 
'This text
can include
line breaks'
WHERE rowid = 1234

pip broke. how to fix DistributionNotFound error?

I had this problem because I installed python/pip with a weird ~/.pydistutils.cfg that I didn't remember writing. Deleted it, reinstalled (with pybrew), and everything was fine.

Using import fs from 'fs'

The new ECMAScript module support is able natively in Node.js 12

It was released on 2019-04-23 and it means there is no need to use the flag --experimental-modules.

To read more about it:

The new ECMAScript module support in Node.js 12

Why can't I inherit static classes?

What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces

Google Maps API - Get Coordinates of address

What you are looking for is called Geocoding.

Google provides a Geocoding Web Service which should do what you're looking for. You will be able to do geocoding on your server.

JSON Example:

http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA

XML Example:

http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA


Edit:

Please note that this is now a deprecated method and you must provide your own Google API key to access this data.

How to get the indexpath.row when an element is activated?

In Swift 4 , just use this:

func buttonTapped(_ sender: UIButton) {
        let buttonPostion = sender.convert(sender.bounds.origin, to: tableView)

        if let indexPath = tableView.indexPathForRow(at: buttonPostion) {
            let rowIndex =  indexPath.row
        }
}

Is there an API to get bank transaction and bank balance?

I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.

Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.

In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.

This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.

OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory

Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx

How to test if a string is JSON or not?

Well... It depends the way you are receiving your data. I think the server is responding with a JSON formated string (using json_encode() in PHP,e.g.). If you're using JQuery post and set response data to be a JSON format and it is a malformed JSON, this will produce an error:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        //Supposing x is a JSON property...
        alert(response.x);

  },
  dataType: 'json',
  //Invalid JSON
  error: function (){ alert("error!"); }
});

But, if you're using the type response as text, you need use $.parseJSON. According jquery site: "Passing in a malformed JSON string may result in an exception being thrown". Thus your code will be:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        try {
            parsedData = JSON.parse(response);
        } catch (e) {
            // is not a valid JSON string
        }

  },
  dataType: 'text',
});

Algorithm for solving Sudoku

I also wrote a Sudoku solver in Python. It is a backtracking algorithm too, but I wanted to share my implementation as well.

Backtracking can be fast enough given that it is moving within the constraints and is choosing cells wisely. You might also want to check out my answer in this thread about optimizing the algorithm. But here I will focus on the algorithm and code itself.

The gist of the algorithm is to start iterating the grid and making decisions what to do - populate a cell, or try another digit for the same cell, or blank out a cell and move back to the previous cell, etc. It's important to note that there is no deterministic way to know how many steps or iterations you will need to solve the puzzle. Therefore, you really have two options - to use a while loop or to use recursion. Both of them can continue iterating until a solution is found or until a lack of solution is proven. The advantage of the recursion is that it is capable of branching out and generally supports more complex logics and algorithms, but the disadvantage is that it is more difficult to implement and often tricky to debug. For my implementation of the backtracking I have used a while loop because no branching is needed, the algorithm searches in a single-threaded linear fashion.

The logic goes like this:

While True: (main iterations)

  1. If all blank cells have been iterated and the last blank cell iterated doesn't have any remaining digits to be tried - stop here because there is no solution.
  2. If there are no blank cells validate the grid. If the grid is valid stop here and return the solution.
  3. If there are blank cells choose the next cell. If that cell has at least on possible digit, assign it and continue to the next main iteration.
  4. If there is at least one remaining choice for the current cell and there are no blank cells or all blank cells have been iterated, assign the remaining choice and continue to the next main iteration.
  5. If none of the above is true, then it is time to backtrack. Blank out the current cell and enter the below loop.

While True: (backtrack iterations)

  1. If there are no more cells to backtrack to - stop here because there is no solution.
  2. Select the previous cell according to the backtracking history.
  3. If the cell doesn't have any choices left, blank out the cell and continue to the next backtrack iteration.
  4. Assign the next available digit to the current cell, break out from backtracking and return to the main iterations.

Some features of the algorithm:

  • it keeps a record of the visited cells in the same order so that it can backtrack at any time

  • it keeps a record of choices for each cell so that it doesn't try the same digit for the same cell twice

  • the available choices for a cell are always within the Sudoku constraints (row, column and 3x3 quadrant)

  • this particular implementation has a few different methods of choosing the next cell and the next digit depending on input parameters (more info in the optimization thread)

  • if given a blank grid, then it will generate a valid Sudoku puzzle (use with optimization parameter "C" in order to generate random grid every time)

  • if given a solved grid it will recognize it and print a message

The full code is:

import random, math, time

class Sudoku:
    def __init__( self, _g=[] ):
        self._input_grid = [] # store a copy of the original input grid for later use
        self.grid = [] # this is the main grid that will be iterated
        for i in _g: # copy the nested lists by value, otherwise Python keeps the reference for the nested lists
            self._input_grid.append( i[:] )
            self.grid.append( i[:] )

    self.empty_cells = set() # set of all currently empty cells (by index number from left to right, top to bottom)
    self.empty_cells_initial = set() # this will be used to compare against the current set of empty cells in order to determine if all cells have been iterated
    self.current_cell = None # used for iterating
    self.current_choice = 0 # used for iterating
    self.history = [] # list of visited cells for backtracking
    self.choices = {} # dictionary of sets of currently available digits for each cell
    self.nextCellWeights = {} # a dictionary that contains weights for all cells, used when making a choice of next cell
    self.nextCellWeights_1 = lambda x: None # the first function that will be called to assign weights
    self.nextCellWeights_2 = lambda x: None # the second function that will be called to assign weights
    self.nextChoiceWeights = {} # a dictionary that contains weights for all choices, used when selecting the next choice
    self.nextChoiceWeights_1 = lambda x: None # the first function that will be called to assign weights
    self.nextChoiceWeights_2 = lambda x: None # the second function that will be called to assign weights

    self.search_space = 1 # the number of possible combinations among the empty cells only, for information purpose only
    self.iterations = 0 # number of main iterations, for information purpose only
    self.iterations_backtrack = 0 # number of backtrack iterations, for information purpose only

    self.digit_heuristic = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0 } # store the number of times each digit is used in order to choose the ones that are least/most used, parameter "3" and "4"
    self.centerWeights = {} # a dictionary of the distances for each cell from the center of the grid, calculated only once at the beginning

    # populate centerWeights by using Pythagorean theorem
    for id in range( 81 ):
        row = id // 9
        col = id % 9
        self.centerWeights[ id ] = int( round( 100 * math.sqrt( (row-4)**2 + (col-4)**2 ) ) )



    # for debugging purposes
    def dump( self, _custom_text, _file_object ):
        _custom_text += ", cell: {}, choice: {}, choices: {}, empty: {}, history: {}, grid: {}\n".format(
            self.current_cell, self.current_choice, self.choices, self.empty_cells, self.history, self.grid )
        _file_object.write( _custom_text )

    # to be called before each solve of the grid
    def reset( self ):
        self.grid = []
        for i in self._input_grid:
            self.grid.append( i[:] )

        self.empty_cells = set()
        self.empty_cells_initial = set()
        self.current_cell = None
        self.current_choice = 0
        self.history = []
        self.choices = {}

        self.nextCellWeights = {}
        self.nextCellWeights_1 = lambda x: None
        self.nextCellWeights_2 = lambda x: None
        self.nextChoiceWeights = {}
        self.nextChoiceWeights_1 = lambda x: None
        self.nextChoiceWeights_2 = lambda x: None

        self.search_space = 1
        self.iterations = 0
        self.iterations_backtrack = 0

        self.digit_heuristic = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0 }

    def validate( self ):
        # validate all rows
        for x in range(9):
            digit_count = { 0:1, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0 }
            for y in range(9):
                digit_count[ self.grid[ x ][ y ] ] += 1
            for i in digit_count:
                if digit_count[ i ] != 1:
                    return False

        # validate all columns
        for x in range(9):
            digit_count = { 0:1, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0 }
            for y in range(9):
                digit_count[ self.grid[ y ][ x ] ] += 1
            for i in digit_count:
                if digit_count[ i ] != 1:
                    return False

        # validate all 3x3 quadrants
        def validate_quadrant( _grid, from_row, to_row, from_col, to_col ):
            digit_count = { 0:1, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0 }
            for x in range( from_row, to_row + 1 ):
                for y in range( from_col, to_col + 1 ):
                    digit_count[ _grid[ x ][ y ] ] += 1
            for i in digit_count:
                if digit_count[ i ] != 1:
                    return False
            return True

        for x in range( 0, 7, 3 ):
            for y in range( 0, 7, 3 ):
                if not validate_quadrant( self.grid, x, x+2, y, y+2 ):
                    return False
        return True

    def setCell( self, _id, _value ):
        row = _id // 9
        col = _id % 9
        self.grid[ row ][ col ] = _value

    def getCell( self, _id ):
        row = _id // 9
        col = _id % 9
        return self.grid[ row ][ col ]

    # returns a set of IDs of all blank cells that are related to the given one, related means from the same row, column or quadrant
    def getRelatedBlankCells( self, _id ):
        result = set()
        row = _id // 9
        col = _id % 9

        for i in range( 9 ):
            if self.grid[ row ][ i ] == 0: result.add( row * 9 + i )
        for i in range( 9 ):
            if self.grid[ i ][ col ] == 0: result.add( i * 9 + col )
        for x in range( (row//3)*3, (row//3)*3 + 3 ):
            for y in range( (col//3)*3, (col//3)*3 + 3 ):
                if self.grid[ x ][ y ] == 0: result.add( x * 9 + y )

        return set( result ) # return by value

    # get the next cell to iterate
    def getNextCell( self ):
        self.nextCellWeights = {}
        for id in self.empty_cells:
            self.nextCellWeights[ id ] = 0

        self.nextCellWeights_1( 1000 ) # these two functions will always be called, but behind them will be a different weight function depending on the optimization parameters provided
        self.nextCellWeights_2( 1 )

        return min( self.nextCellWeights, key = self.nextCellWeights.get )

    def nextCellWeights_A( self, _factor ): # the first cell from left to right, from top to bottom
        for id in self.nextCellWeights:
            self.nextCellWeights[ id ] += id * _factor

    def nextCellWeights_B( self, _factor ): # the first cell from right to left, from bottom to top
        self.nextCellWeights_A( _factor * -1 )

    def nextCellWeights_C( self, _factor ): # a randomly chosen cell
        for id in self.nextCellWeights:
            self.nextCellWeights[ id ] += random.randint( 0, 999 ) * _factor

    def nextCellWeights_D( self, _factor ): # the closest cell to the center of the grid
        for id in self.nextCellWeights:
            self.nextCellWeights[ id ] += self.centerWeights[ id ] * _factor

    def nextCellWeights_E( self, _factor ): # the cell that currently has the fewest choices available
        for id in self.nextCellWeights:
            self.nextCellWeights[ id ] += len( self.getChoices( id ) ) * _factor

    def nextCellWeights_F( self, _factor ): # the cell that currently has the most choices available
        self.nextCellWeights_E( _factor * -1 )

    def nextCellWeights_G( self, _factor ): # the cell that has the fewest blank related cells
        for id in self.nextCellWeights:
            self.nextCellWeights[ id ] += len( self.getRelatedBlankCells( id ) ) * _factor

    def nextCellWeights_H( self, _factor ): # the cell that has the most blank related cells
        self.nextCellWeights_G( _factor * -1 )

    def nextCellWeights_I( self, _factor ): # the cell that is closest to all filled cells
        for id in self.nextCellWeights:
            weight = 0
            for check in range( 81 ):
                if self.getCell( check ) != 0:
                    weight += math.sqrt( ( id//9 - check//9 )**2 + ( id%9 - check%9 )**2 )

    def nextCellWeights_J( self, _factor ): # the cell that is furthest from all filled cells
        self.nextCellWeights_I( _factor * -1 )

    def nextCellWeights_K( self, _factor ): # the cell whose related blank cells have the fewest available choices
        for id in self.nextCellWeights:
            weight = 0
            for id_blank in self.getRelatedBlankCells( id ):
                weight += len( self.getChoices( id_blank ) )
            self.nextCellWeights[ id ] += weight * _factor

    def nextCellWeights_L( self, _factor ): # the cell whose related blank cells have the most available choices
        self.nextCellWeights_K( _factor * -1 )



    # for a given cell return a set of possible digits within the Sudoku restrictions
    def getChoices( self, _id ):
        available_choices = {1,2,3,4,5,6,7,8,9}
        row = _id // 9
        col = _id % 9

        # exclude digits from the same row
        for y in range( 0, 9 ):
            if self.grid[ row ][ y ] in available_choices:
                available_choices.remove( self.grid[ row ][ y ] )

        # exclude digits from the same column
        for x in range( 0, 9 ):
            if self.grid[ x ][ col ] in available_choices:
                available_choices.remove( self.grid[ x ][ col ] )

        # exclude digits from the same quadrant
        for x in range( (row//3)*3, (row//3)*3 + 3 ):
            for y in range( (col//3)*3, (col//3)*3 + 3 ):
                if self.grid[ x ][ y ] in available_choices:
                    available_choices.remove( self.grid[ x ][ y ] )

        if len( available_choices ) == 0: return set()
        else: return set( available_choices ) # return by value

    def nextChoice( self ):
        self.nextChoiceWeights = {}
        for i in self.choices[ self.current_cell ]:
            self.nextChoiceWeights[ i ] = 0

        self.nextChoiceWeights_1( 1000 )
        self.nextChoiceWeights_2( 1 )

        self.current_choice = min( self.nextChoiceWeights, key = self.nextChoiceWeights.get )
        self.setCell( self.current_cell, self.current_choice )
        self.choices[ self.current_cell ].remove( self.current_choice )

    def nextChoiceWeights_0( self, _factor ): # the lowest digit
        for i in self.nextChoiceWeights:
            self.nextChoiceWeights[ i ] += i * _factor

    def nextChoiceWeights_1( self, _factor ): # the highest digit
        self.nextChoiceWeights_0( _factor * -1 )

    def nextChoiceWeights_2( self, _factor ): # a randomly chosen digit
        for i in self.nextChoiceWeights:
            self.nextChoiceWeights[ i ] += random.randint( 0, 999 ) * _factor

    def nextChoiceWeights_3( self, _factor ): # heuristically, the least used digit across the board
        self.digit_heuristic = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0 }
        for id in range( 81 ):
            if self.getCell( id ) != 0: self.digit_heuristic[ self.getCell( id ) ] += 1
        for i in self.nextChoiceWeights:
            self.nextChoiceWeights[ i ] += self.digit_heuristic[ i ] * _factor

    def nextChoiceWeights_4( self, _factor ): # heuristically, the most used digit across the board
        self.nextChoiceWeights_3( _factor * -1 )

    def nextChoiceWeights_5( self, _factor ): # the digit that will cause related blank cells to have the least number of choices available
        cell_choices = {}
        for id in self.getRelatedBlankCells( self.current_cell ):
            cell_choices[ id ] = self.getChoices( id )

        for c in self.nextChoiceWeights:
            weight = 0
            for id in cell_choices:
                weight += len( cell_choices[ id ] )
                if c in cell_choices[ id ]: weight -= 1
            self.nextChoiceWeights[ c ] += weight * _factor

    def nextChoiceWeights_6( self, _factor ): # the digit that will cause related blank cells to have the most number of choices available
        self.nextChoiceWeights_5( _factor * -1 )

    def nextChoiceWeights_7( self, _factor ): # the digit that is the least common available choice among related blank cells
        cell_choices = {}
        for id in self.getRelatedBlankCells( self.current_cell ):
            cell_choices[ id ] = self.getChoices( id )

        for c in self.nextChoiceWeights:
            weight = 0
            for id in cell_choices:
                if c in cell_choices[ id ]: weight += 1
            self.nextChoiceWeights[ c ] += weight * _factor

    def nextChoiceWeights_8( self, _factor ): # the digit that is the most common available choice among related blank cells
        self.nextChoiceWeights_7( _factor * -1 )

    def nextChoiceWeights_9( self, _factor ): # the digit that is the least common available choice across the board
        cell_choices = {}
        for id in range( 81 ):
            if self.getCell( id ) == 0:
                cell_choices[ id ] = self.getChoices( id )

        for c in self.nextChoiceWeights:
            weight = 0
            for id in cell_choices:
                if c in cell_choices[ id ]: weight += 1
            self.nextChoiceWeights[ c ] += weight * _factor

    def nextChoiceWeights_a( self, _factor ): # the digit that is the most common available choice across the board
        self.nextChoiceWeights_9( _factor * -1 )



    # the main function to be called
    def solve( self, _nextCellMethod, _nextChoiceMethod, _start_time, _prefillSingleChoiceCells = False ):
        s = self
        s.reset()

        # initialize optimization functions based on the optimization parameters provided
        """
        A - the first cell from left to right, from top to bottom
        B - the first cell from right to left, from bottom to top
        C - a randomly chosen cell
        D - the closest cell to the center of the grid
        E - the cell that currently has the fewest choices available
        F - the cell that currently has the most choices available
        G - the cell that has the fewest blank related cells
        H - the cell that has the most blank related cells
        I - the cell that is closest to all filled cells
        J - the cell that is furthest from all filled cells
        K - the cell whose related blank cells have the fewest available choices
        L - the cell whose related blank cells have the most available choices
        """
        if _nextCellMethod[ 0 ] in "ABCDEFGHIJKLMN":
            s.nextCellWeights_1 = getattr( s, "nextCellWeights_" + _nextCellMethod[0] )
        elif _nextCellMethod[ 0 ] == " ":
            s.nextCellWeights_1 = lambda x: None
        else:
            print( "(A) Incorrect optimization parameters provided" )
            return False

        if len( _nextCellMethod ) > 1:
            if _nextCellMethod[ 1 ] in "ABCDEFGHIJKLMN":
                s.nextCellWeights_2 = getattr( s, "nextCellWeights_" + _nextCellMethod[1] )
            elif _nextCellMethod[ 1 ] == " ":
                s.nextCellWeights_2 = lambda x: None
            else:
                print( "(B) Incorrect optimization parameters provided" )
                return False
        else:
            s.nextCellWeights_2 = lambda x: None

        # initialize optimization functions based on the optimization parameters provided
        """
        0 - the lowest digit
        1 - the highest digit
        2 - a randomly chosen digit
        3 - heuristically, the least used digit across the board
        4 - heuristically, the most used digit across the board
        5 - the digit that will cause related blank cells to have the least number of choices available
        6 - the digit that will cause related blank cells to have the most number of choices available
        7 - the digit that is the least common available choice among related blank cells
        8 - the digit that is the most common available choice among related blank cells
        9 - the digit that is the least common available choice across the board
        a - the digit that is the most common available choice across the board
        """
        if _nextChoiceMethod[ 0 ] in "0123456789a":
            s.nextChoiceWeights_1 = getattr( s, "nextChoiceWeights_" + _nextChoiceMethod[0] )
        elif _nextChoiceMethod[ 0 ] == " ":
            s.nextChoiceWeights_1 = lambda x: None
        else:
            print( "(C) Incorrect optimization parameters provided" )
            return False

        if len( _nextChoiceMethod ) > 1:
            if _nextChoiceMethod[ 1 ] in "0123456789a":
                s.nextChoiceWeights_2 = getattr( s, "nextChoiceWeights_" + _nextChoiceMethod[1] )
            elif _nextChoiceMethod[ 1 ] == " ":
                s.nextChoiceWeights_2 = lambda x: None
            else:
                print( "(D) Incorrect optimization parameters provided" )
                return False
        else:
            s.nextChoiceWeights_2 = lambda x: None

        # fill in all cells that have single choices only, and keep doing it until there are no left, because as soon as one cell is filled this might bring the choices down to 1 for another cell
        if _prefillSingleChoiceCells == True:
            while True:
                next = False
                for id in range( 81 ):
                    if s.getCell( id ) == 0:
                        cell_choices = s.getChoices( id )
                        if len( cell_choices ) == 1:
                            c = cell_choices.pop()
                            s.setCell( id, c )
                            next = True
                if not next: break

        # initialize set of empty cells
        for x in range( 0, 9, 1 ):
            for y in range( 0, 9, 1 ):
                if s.grid[ x ][ y ] == 0:
                    s.empty_cells.add( 9*x + y )
        s.empty_cells_initial = set( s.empty_cells ) # copy by value

        # calculate search space
        for id in s.empty_cells:
            s.search_space *= len( s.getChoices( id ) )

        # initialize the iteration by choosing a first cell
        if len( s.empty_cells ) < 1:
            if s.validate():
                print( "Sudoku provided is valid!" )
                return True
            else:
                print( "Sudoku provided is not valid!" )
                return False
        else: s.current_cell = s.getNextCell()

        s.choices[ s.current_cell ] = s.getChoices( s.current_cell )
        if len( s.choices[ s.current_cell ] ) < 1:
            print( "(C) Sudoku cannot be solved!" )
            return False



        # start iterating the grid
        while True:
            #if time.time() - _start_time > 2.5: return False # used when doing mass tests and don't want to wait hours for an inefficient optimization to complete

            s.iterations += 1

            # if all empty cells and all possible digits have been exhausted, then the Sudoku cannot be solved
            if s.empty_cells == s.empty_cells_initial and len( s.choices[ s.current_cell ] ) < 1:
                print( "(A) Sudoku cannot be solved!" )
                return False

            # if there are no empty cells, it's time to validate the Sudoku
            if len( s.empty_cells ) < 1:
                if s.validate():
                    print( "Sudoku has been solved! " )
                    print( "search space is {}".format( self.search_space ) )
                    print( "empty cells: {}, iterations: {}, backtrack iterations: {}".format( len( self.empty_cells_initial ), self.iterations, self.iterations_backtrack ) )
                    for i in range(9):
                        print( self.grid[i] )
                    return True

            # if there are empty cells, then move to the next one
            if len( s.empty_cells ) > 0:

                s.current_cell = s.getNextCell() # get the next cell
                s.history.append( s.current_cell ) # add the cell to history
                s.empty_cells.remove( s.current_cell ) # remove the cell from the empty queue
                s.choices[ s.current_cell ] = s.getChoices( s.current_cell ) # get possible choices for the chosen cell

                if len( s.choices[ s.current_cell ] ) > 0: # if there is at least one available digit, then choose it and move to the next iteration, otherwise the iteration continues below with a backtrack
                    s.nextChoice()
                    continue

            # if all empty cells have been iterated or there are no empty cells, and there are still some remaining choices, then try another choice
            if len( s.choices[ s.current_cell ] ) > 0 and ( s.empty_cells == s.empty_cells_initial or len( s.empty_cells ) < 1 ): 
                s.nextChoice()
                continue

            # if none of the above, then we need to backtrack to a cell that was previously iterated
            # first, restore the current cell...
            s.history.remove( s.current_cell ) # ...by removing it from history
            s.empty_cells.add( s.current_cell ) # ...adding back to the empty queue
            del s.choices[ s.current_cell ] # ...scrapping all choices
            s.current_choice = 0
            s.setCell( s.current_cell, s.current_choice ) # ...and blanking out the cell

            # ...and then, backtrack to a previous cell
            while True:
                s.iterations_backtrack += 1

                if len( s.history ) < 1:
                    print( "(B) Sudoku cannot be solved!" )
                    return False

                s.current_cell = s.history[ -1 ] # after getting the previous cell, do not recalculate all possible choices because we will lose the information about has been tried so far

                if len( s.choices[ s.current_cell ] ) < 1: # backtrack until a cell is found that still has at least one unexplored choice...
                    s.history.remove( s.current_cell )
                    s.empty_cells.add( s.current_cell )
                    s.current_choice = 0
                    del s.choices[ s.current_cell ]
                    s.setCell( s.current_cell, s.current_choice )
                    continue

                # ...and when such cell is found, iterate it
                s.nextChoice()
                break # and break out from the backtrack iteration but will return to the main iteration

Example call using the world's hardest Sudoku as per this article http://www.telegraph.co.uk/news/science/science-news/9359579/Worlds-hardest-sudoku-can-you-crack-it.html

hardest_sudoku = [
    [8,0,0,0,0,0,0,0,0],
    [0,0,3,6,0,0,0,0,0],
    [0,7,0,0,9,0,2,0,0],
    [0,5,0,0,0,7,0,0,0],
    [0,0,0,0,4,5,7,0,0],
    [0,0,0,1,0,0,0,3,0],
    [0,0,1,0,0,0,0,6,8],
    [0,0,8,5,0,0,0,1,0],
    [0,9,0,0,0,0,4,0,0]]

mySudoku = Sudoku( hardest_sudoku )
start = time.time()
mySudoku.solve( "A", "0", time.time(), False )
print( "solved in {} seconds".format( time.time() - start ) )

And example output is:

Sudoku has been solved!
search space is 9586591201964851200000000000000000000
empty cells: 60, iterations: 49559, backtrack iterations: 49498
[8, 1, 2, 7, 5, 3, 6, 4, 9]
[9, 4, 3, 6, 8, 2, 1, 7, 5]
[6, 7, 5, 4, 9, 1, 2, 8, 3]
[1, 5, 4, 2, 3, 7, 8, 9, 6]
[3, 6, 9, 8, 4, 5, 7, 2, 1]
[2, 8, 7, 1, 6, 9, 5, 3, 4]
[5, 2, 1, 9, 7, 4, 3, 6, 8]
[4, 3, 8, 5, 2, 6, 9, 1, 7]
[7, 9, 6, 3, 1, 8, 4, 5, 2]
solved in 1.1600663661956787 seconds

iOS Launching Settings -> Restrictions URL Scheme

Here is something else I found:

  1. After I have the "prefs" URL Scheme defined, "prefs:root=Safari&path=ContentBlockers" is working on Simulator (iOS 9.1 English), but not working on Simulator (Simplified Chinese). It just jump to Safari, but not Content Blockers. If your app is international, be careful.
    Update: Don't know why, now I can't jump into ContentBlockers anymore, the same code, the same version, doesn't work now. :(

  2. On real devcies (mine is iPhone 6S & iPad mini 2), "Safari" should be "SAFARI", "Safari" not working on real device, "SAFARI" now working on simulator:

    #if arch(i386) || arch(x86_64)
        // Simulator
        let url = NSURL(string: "prefs:root=Safari")!
    #else
        // Device
        let url = NSURL(string: "prefs:root=SAFARI")!
    #endif
    
    if UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.sharedApplication().openURL(url)
    }
    
  3. So far, did not find any differences between iPhone and iPad.

"Exception has been thrown by the target of an invocation" error (mscorlib)

I'd suggest checking for an inner exception. If there isn't one, check your logs for the exception that occurred immediately prior to this one.

This isn't a web-specific exception, I've also encountered it in desktop-app development. In short, what's happening is that the thread receiving this exception is running some asynchronous code (via Invoke(), e.g.) and that code that's being run asynchronously is exploding with an exception. This target invocation exception is the aftermath of that failure.

If you haven't already, place some sort of exception logging wrapper around the asynchronous callbacks that are being invoked when you trigger this error. Event handlers, for instance. That ought to help you track down the problem.

Good luck!

How do you disable viewport zooming on Mobile Safari?

@mattis is correct that iOS 10 Safari won't allow you to disable pinch to zoom with the user-scalable attribute. However, I got it to disable using preventDefault on the 'gesturestart' event. I've only verified this on Safari in iOS 10.0.2.

document.addEventListener('gesturestart', function (e) {
    e.preventDefault();
});

How can I initialize a MySQL database with schema in a Docker container?

After Aug. 4, 2015, if you are using the official mysql Docker image, you can just ADD/COPY a file into the /docker-entrypoint-initdb.d/ directory and it will run with the container is initialized. See github: https://github.com/docker-library/mysql/commit/14f165596ea8808dfeb2131f092aabe61c967225 if you want to implement it on other container images

How do I delete a local repository in git?

In the repository directory you remove the directory named .git and that's all :). On Un*x it is hidden, so you might not see it from file browser, but

cd repository-path/
rm -r .git

should do the trick.

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

How to leave/exit/deactivate a Python virtualenv

I defined an alias, workoff, as the opposite of workon:

alias workoff='deactivate'

It is easy to remember:

[bobstein@host ~]$ workon django_project
(django_project)[bobstein@host ~]$ workoff
[bobstein@host ~]$

How can I get query parameters from a URL in Vue.js?

More detailed answer to help the newbies of VueJS:

  • First define your router object, select the mode you seem fit. You can declare your routes inside the routes list.
  • Next you would want your main app to know router exists, so declare it inside the main app declaration .
  • Lastly they $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready , .ie its called as soon as the app is ready)

And the code itself:

<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
    mode: 'history',
    routes: []
});
var vm =  new Vue({
    router,
    el: '#app',
    mounted: function() {
        q = this.$route.query.q
        console.log(q)
    },
});

JPA & Criteria API - Select only specific columns

One of the JPA ways for getting only particular columns is to ask for a Tuple object.

In your case you would need to write something like this:

CriteriaQuery<Tuple> cq = builder.createTupleQuery();
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<Tuple> tupleResult = em.createQuery(cq).getResultList();
for (Tuple t : tupleResult) {
    Long id = (Long) t.get(0);
    Long version = (Long) t.get(1);
}

Another approach is possible if you have a class representing the result, like T in your case. T doesn't need to be an Entity class. If T has a constructor like:

public T(Long id, Long version)

then you can use T directly in your CriteriaQuery constructor:

CriteriaQuery<T> cq = builder.createQuery(T.class);
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<T> result = em.createQuery(cq).getResultList();

See this link for further reference.

Can I call a constructor from another constructor (do constructor chaining) in C++?

If I understand your question correctly, you're asking if you can call multiple constructors in C++?

If that's what you're looking for, then no - that is not possible.

You certainly can have multiple constructors, each with unique argument signatures, and then call the one you want when you instantiate a new object.

You can even have one constructor with defaulted arguments on the end.

But you may not have multiple constructors, and then call each of them separately.

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

CHECK constraint in MySQL is not working

The CHECK constraint doesn't seem to be implemented in MySQL.

See this bug report: https://bugs.mysql.com/bug.php?id=3464

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

Using the "With Clause" SQL Server 2008

Try the sp_foreachdb procedure.

Python regex for integer?

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers with a sign could be for example

^[-+]?[0-9]+$

meaning

  1. ^ - start of string
  2. [-+]? - an optional (this is what ? means) minus or plus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string

Note: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2 could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Try this:

<div id="wrapper">
    <div class="float left">left</div>
    <div class="float right">right</div>
</div>

#wrapper {
   width:500px; 
   height:300px; 
   position:relative;
}

.float {
   background-color:black; 
   height:300px; 
   margin:0; 
   padding:0; 
   color:white;
}

.left {
   background-color:blue; 
   position:fixed; 
   width:400px;
}

.right {
   float:right; 
   width:100px;
}

jsFiddle: http://jsfiddle.net/khA4m

Truncating long strings with CSS: feasible yet?

Update: text-overflow: ellipsis is now supported as of Firefox 7 (released September 27th 2011). Yay! My original answer follows as a historical record.

Justin Maxwell has cross browser CSS solution. It does come with the downside however of not allowing the text to be selected in Firefox. Check out his guest post on Matt Snider's blog for the full details on how this works.

Note this technique also prevents updating the content of the node in JavaScript using the innerHTML property in Firefox. See the end of this post for a workaround.

CSS

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}

ellipsis.xml file contents

<?xml version="1.0"?>
<bindings
  xmlns="http://www.mozilla.org/xbl"
  xmlns:xbl="http://www.mozilla.org/xbl"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
    <binding id="ellipsis">
        <content>
            <xul:window>
                <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
            </xul:window>
        </content>
    </binding>
</bindings>

Updating node content

To update the content of a node in a way that works in Firefox use the following:

var replaceEllipsis(node, content) {
    node.innerHTML = content;
    // use your favorite framework to detect the gecko browser
    if (YAHOO.env.ua.gecko) {
        var pnode = node.parentNode,
            newNode = node.cloneNode(true);

        pnode.replaceChild(newNode, node);
    }
};

See Matt Snider's post for an explanation of how this works.

How to define static constant in a class in swift

Tried on Playground


class MyClass {

struct Constants { static let testStr = "test" static let testStrLen = testStr.characters.count //testInt will not be accessable by other classes in different swift files private static let testInt = 1 static func singletonFunction() { //accessable print("Print singletonFunction testInt=\(testInt)") var newInt = testStrLen newInt = newInt + 1 print("Print singletonFunction testStr=\(testStr)") } } func ownFunction() { //not accessable //var newInt1 = Constants.testInt + 1 var newInt2 = Constants.testStrLen newInt2 = newInt2 + 1 print("Print ownFunction testStr=\(Constants.testStr)") print("Print ownFunction newInt2=\(newInt2)") } } let newInt = MyClass.Constants.testStrLen print("Print testStr=\(MyClass.Constants.testStr)") print("Print testInt=\(newInt)") let myClass = MyClass() myClass.ownFunction() MyClass.Constants.singletonFunction()

Difference between links and depends_on in docker_compose.yml

[Update Sep 2016]: This answer was intended for docker compose file v1 (as shown by the sample compose file below). For v2, see the other answer by @Windsooon.

[Original answer]:

It is pretty clear in the documentation. depends_on decides the dependency and the order of container creation and links not only does these, but also

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

For example, assuming the following docker-compose.yml file:

web:
  image: example/my_web_app:latest
  links:
    - db
    - cache

db:
  image: postgres:latest

cache:
  image: redis:latest

With links, code inside web will be able to access the database using db:5432, assuming port 5432 is exposed in the db image. If depends_on were used, this wouldn't be possible, but the startup order of the containers would be correct.

How to create multiple class objects with a loop in python?

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()

Java2D: Increase the line width

What is Stroke:

The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which are rendered with a Graphics2D object that has its Stroke attribute set to this BasicStroke.

https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html

Note that the Stroke setting:

Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));

is setting the line width,since BasicStroke(float width):

Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.

And, it also effects other methods like Graphics2D.drawLine(int x1, int y1, int x2, int y2) and Graphics2D.drawRect(int x, int y, int width, int height):

The methods of the Graphics2D interface that use the outline Shape returned by a Stroke object include draw and any other methods that are implemented in terms of that method, such as drawLine, drawRect, drawRoundRect, drawOval, drawArc, drawPolyline, and drawPolygon.

How to get pandas.DataFrame columns containing specific dtype

To get the column names from pandas dataframe in python3- Here I am creating a data frame from a fileName.csv file

>>> import pandas as pd
>>> df = pd.read_csv('fileName.csv')
>>> columnNames = list(df.head(0)) 
>>> print(columnNames)

How do I convert a datetime to date?

You can convert a datetime object to a date with the date() method of the date time object, as follows:

<datetime_object>.date()

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You will have to use the fluent API to do this.

Try adding the following to your DbContext:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{   
    modelBuilder.Entity<User>()
        .HasOptional(a => a.UserDetail)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

CSS3 background image transition

Try this, will make the background animated worked on web but hybrid mobile app not working

@-webkit-keyframes breath {
 0%   {  background-size: 110% auto; }
 50%  {  background-size: 140% auto; }
 100% {  background-size: 110% auto; }      
}
body {
   -webkit-animation: breath 15s linear infinite;
   background-image: url(images/login.png);
    background-size: cover;
}

Group by month and year in MySQL

I know this is an old question, but the following should work if you don't need the month name at the DB level:

  SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month 
    FROM trading_summary  
GROUP BY summary_year_month;

See EXTRACT function docs

You will probably find this to be better performing.. and if you are building a JSON object in the application layer, you can do the formatting/ordering as you run through the results.

N.B. I wasn't aware you could add DESC to a GROUP BY clause in MySQL, perhaps you are missing an ORDER BY clause:

  SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month 
    FROM trading_summary  
GROUP BY summary_year_month
ORDER BY summary_year_month DESC;

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

How do I access the HTTP request header fields via JavaScript?

If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.

To retrieve the referrer, use document.referrer.
To access the user-agent, use navigator.userAgent.

As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.

How do I commit case-sensitive only filename changes in Git?

When you've done a lot of file renaming and some of it are just a change of casing, it's hard to remember which is which. manually "git moving" the file can be quite some work. So what I would do during my filename change tasks are:

  1. remove all non-git files and folder to a different folder/repository.
  2. commit current empty git folder (this will show as all files deleted.)
  3. add all the files back into the original git folder/repository.
  4. commit current non-empty git folder.

This will fix all the case issues without trying to figure out which files or folders you renamed.

How to get file name when user select a file via <input type="file" />?

You can use the next code:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

How about adding this to your pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
</dependency>

New line in JavaScript alert box

use the new line character of a javascript instead of '\n'.. eg: "Hello\nWorld" use "Hello\x0AWorld" It works great!!

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Check the minimum API level inside the build.gradle(module: app)[inside of the gradle scripts]. Thatt should be equal to or lower than the device you use

How to check the version before installing a package using apt-get?

Also, the apt-show-versions package (installed separately) parses dpkg information about what is installed and tells you if packages are up to date.

Example..

$ sudo apt-show-versions --regex chrome
google-chrome-stable/stable upgradeable from 32.0.1700.102-1 to 35.0.1916.114-1
xserver-xorg-video-openchrome/quantal-security uptodate 1:0.3.1-0ubuntu1.12.10.1
$

Windows recursive grep command-line

Recursive search for import word inside src folder:

> findstr /s import .\src\*

MySQL: When is Flush Privileges in MySQL really needed?

Just to give some examples. Let's say you modify the password for an user called 'alex'. You can modify this password in several ways. For instance:

mysql> update* user set password=PASSWORD('test!23') where user='alex'; 
mysql> flush privileges;

Here you used UPDATE. If you use INSERT, UPDATE or DELETE on grant tables directly you need use FLUSH PRIVILEGES in order to reload the grant tables.

Or you can modify the password like this:

mysql> set password for 'alex'@'localhost'= password('test!24');

Here it's not necesary to use "FLUSH PRIVILEGES;" If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.

CSS: Fix row height

Simply add style="line-height:0" to each cell. This works in IE because it sets the line-height of both existant and non-existant text to about 19px and that forces the cells to expand vertically in most versions of IE. Regardless of whether or not you have text this needs to be done for IE to correctly display rows less than 20px high.

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

What is the "realm" in basic authentication

A realm can be seen as an area (not a particular page, it could be a group of pages) for which the credentials are used; this is also the string that will be shown when the browser pops up the login window, e.g.

Please enter your username and password for <realm name>:

When the realm changes, the browser may show another popup window if it doesn't have credentials for that particular realm.

System.BadImageFormatException: Could not load file or assembly

I had the same exception installing using correct framework.

My solution was running cmd as administrator .... then it worked fine.

Pick any kind of file via an Intent in Android

this work for me on galaxy note its show contacts, file managers installed on device, gallery, music player

private void openFile(Int  CODE) {
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.setType("*/*");
    startActivityForResult(intent, CODE);
}

here get path in onActivityResult of activity.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     String Fpath = data.getDataString();
    // do somthing...
    super.onActivityResult(requestCode, resultCode, data);

}

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Checking Maven Version

You need to add path to svn.exe file to system environment, variable PATH, after that you can run command mvn from any folder. You can do it from command line(cmd.exe) like this, for example:

set PATH=%PATH%;C:\maven\bin

Or you can got to the folder where mvn.exe is, and run your command there.

And you need not mvn -version, but mvn --version parameter.

scp with port number specified

for use another port on scp command use capital P like this

scp -P port-number source-file/directory user@domain:/destination

ya ali

How to clear basic authentication details in chrome

May be old thread but thought of adding answer to help others.

I had the same issue with Advanced ReST Client App, I'm not able to clear basic authentication from Chrome neither from app. It simply stopped asking for credentials!

However, I managed to make it work by relaunching Chrome using About Google Chrome -> Relaunch.

Once Chrome is relaunched, when I accessed ReST service, it will ask for user name and password using basic authentication popup.

Hope this helps!

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

How do you do exponentiation in C?

The non-recursive version of the function is not too hard - here it is for integers:

long powi(long x, unsigned n)
{
    long p = x;
    long r = 1;

    while (n > 0)
    {
        if (n % 2 == 1)
            r *= p;
        p *= p;
        n /= 2;
    }

    return(r);
}

(Hacked out of code for raising a double value to an integer power - had to remove the code to deal with reciprocals, for example.)

How do you perform address validation?

One area where address lookups have to be performed reliably is for VOIP E911 services. I know companies reliably using the following services for this:

Bandwidth.com 9-1-1 Access API MSAG Address Validation

MSAG = Master Street Address Guide

https://www.bandwidth.com/9-1-1/

SmartyStreet US Street Address API

https://smartystreets.com/docs/cloud/us-street-api

Current Subversion revision command

Otherwise for old version, if '--show-item' is not recognize, you can use the following command :

svn log -r HEAD | grep -o -E "^r[0-9]{1,}" | sed 's/r//g'

Hope it helps.

How can I disable the bootstrap hover color for links?

Mark color: #005580; as color: #005580 !important;.

It will override default bootstrap hover.

Class extending more than one class Java?

There is no concept of multiple inheritance in Java. Only multiple interfaces can be implemented.

What are the most useful Intellij IDEA keyboard shortcuts?

http://www.jetbrains.com/idea/docs/ReferenceCard70_mac.pdf has everything you need. after a while, you'll develop your own preference for certain shortcuts.

laravel 5.5 The page has expired due to inactivity. Please refresh and try again

In my case the same problem was caused because I forgot to add > at the end of my hidden input field, like so: <input type="hidden" name="_token" value="{{ Session::token() }}"

So, I fixed it by adding it:

<input type="hidden" name="_token" value="{{ Session::token() }}">

Reverse engineering from an APK file to a project

For the Android platform, you can try ShowJava, available on the Play Store.

You can consult the generated code through the app interface and the generated java files and folders structure are stored in ShowJava folder in /sdcard, alongside the resulting .jar file from the conversion.

The app is free with an ad banner at the bottom of the main view, but there is an in-app purchase option (3,99$) to remove it. In-app purchase does not add any functionality beside removing the ad banner.

Disclosure : I'm not the developer of the app neither I'm affiliated with him in any way.

Inserting line breaks into PDF

The solution I've found was:

$text = 'Line one\n\nLine two');
$text = explode('\n', $text);

foreach ($text as $txt){
    $pdf->Write($txt);
    $pdf->Ln();
}

So this way, you may have any number of \n in any position, if you're getting this text dinamically from the database, it will break lines correctrly.

How to play a sound in C#, .NET

To play an Audio file in the Windows form using C# let's check simple example as follows :

1.Go Visual Studio(VS-2008/2010/2012) --> File Menu --> click New Project.

2.In the New Project --> click Windows Forms Application --> Give Name and then click OK.

A new "Windows Forms" project will opens.

3.Drag-and-Drop a Button control from the Toolbox to the Windows Form.

4.Double-click the button to create automatically the default Click event handler, and add the following code.

This code displays the File Open dialog box and passes the results to a method named "playSound" that you will create in the next step.

 OpenFileDialog dialog = new OpenFileDialog();
 dialog.Filter = "Audio Files (.wav)|*.wav";


if(dialog.ShowDialog() == DialogResult.OK)
{
  string path = dialog.FileName;
  playSound(path);
}

5.Add the following method code under the button1_Click event hander.

 private void playSound(string path)
 {
   System.Media.SoundPlayer player = new System.Media.SoundPlayer();
   player.SoundLocation = path;
   player.Load();
   player.Play();
 }

6.Now let's run the application just by Pressing the F5 to run the code.

7.Click the button and select an audio file. After the file loads, the sound will play.

I hope this is useful example to beginners...

How to set div width using ng-style

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

Convert an image to grayscale in HTML/CSS

Update: I made this into a full GitHub repo, including JavaScript polyfill for IE10 and IE11: https://github.com/karlhorky/gray

I originally used SalmanPK's answer, but then created the variation below to eliminate the extra HTTP request required for the SVG file. The inline SVG works in Firefox versions 10 and above, and versions lower than 10 no longer account for even 1% of the global browser market.

I have since been keeping the solution updated on this blog post, adding support for fading back to color, IE 10/11 support with SVG, and partial grayscale in the demo.

img.grayscale {
  /* Firefox 10+, Firefox on Android */
  filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0'/></filter></svg>#grayscale");

  /* IE 6-9 */
  filter: gray;

  /* Chrome 19+, Safari 6+, Safari 6+ iOS */
  -webkit-filter: grayscale(100%);
}

img.grayscale.disabled {
  filter: none;
  -webkit-filter: grayscale(0%);
}

How to make program go back to the top of the code instead of closing

You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.

Copy data into another table

Simple way if new table does not exist and you want to make a copy of old table with everything then following works in SQL Server.

SELECT * INTO NewTable FROM OldTable

Hide/Show components in react native

in render() you can conditionally show the JSX or return null as in:

render(){
    return({yourCondition ? <yourComponent /> : null});
}

Deserialize from string instead TextReader

static T DeserializeXml<T>(string sourceXML) where T : class
{
    var serializer = new XmlSerializer(typeof(T));
    T result = null;

    using (TextReader reader = new StringReader(sourceXML))
    {
        result = (T) serializer.Deserialize(reader);
    }

    return result;
}

Differences between time complexity and space complexity?

Time and Space complexity are different aspects of calculating the efficiency of an algorithm.

Time complexity deals with finding out how the computational time of an algorithm changes with the change in size of the input.

On the other hand, space complexity deals with finding out how much (extra)space would be required by the algorithm with change in the input size.

To calculate time complexity of the algorithm the best way is to check if we increase in the size of the input, will the number of comparison(or computational steps) also increase and to calculate space complexity the best bet is to see additional memory requirement of the algorithm also changes with the change in the size of the input.

A good example could be of Bubble sort.

Lets say you tried to sort an array of 5 elements. In the first pass you will compare 1st element with next 4 elements. In second pass you will compare 2nd element with next 3 elements and you will continue this procedure till you fully exhaust the list.

Now what will happen if you try to sort 10 elements. In this case you will start with comparing comparing 1st element with next 9 elements, then 2nd with next 8 elements and so on. In other words if you have N element array you will start of by comparing 1st element with N-1 elements, then 2nd element with N-2 elements and so on. This results in O(N^2) time complexity.

But what about size. When you sorted 5 element or 10 element array did you use any additional buffer or memory space. You might say Yes, I did use a temporary variable to make the swap. But did the number of variables changed when you increased the size of array from 5 to 10. No, Irrespective of what is the size of the input you will always use a single variable to do the swap. Well, this means that the size of the input has nothing to do with the additional space you will require resulting in O(1) or constant space complexity.

Now as an exercise for you, research about the time and space complexity of merge sort

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Go to the following setting:

Window -> Preferences -> Java-Compiler-Errors/Warnings-Deprecated and restricted API-Forbidden reference (access rules)

Set it to Warning or Ignore.

Iterate a certain number of times without storing the iteration number anywhere

exec 'print "hello";' * 2

should work, but I'm kind of ashamed that I thought of it.

Update: Just thought of another one:

for _ in " "*10: print "hello"

Storing images in SQL Server?

Another option was released in 2012 called File tables: https://msdn.microsoft.com/en-us/library/ff929144.aspx

Update records using LINQ

I assume person_id is the primary key of Person table, so here's how you update a single record:

Person result = (from p in Context.Persons
              where p.person_id == 5
              select p).SingleOrDefault();

result.is_default = false;

Context.SaveChanges();

and here's how you update multiple records:

List<Person> results = (from p in Context.Persons
                        where .... // add where condition here
                        select p).ToList();

foreach (Person p in results)
{
    p.is_default = false;
}

Context.SaveChanges();

Simple way to create matrix of random numbers

#this is a function for a square matrix so on the while loop rows does not have to be less than cols.
#you can make your own condition. But if you want your a square matrix, use this code.

import random

import numpy as np

def random_matrix(R, cols):

        matrix = []

        rows =  0

        while  rows < cols:

            N = random.sample(R, cols)

            matrix.append(N)

            rows = rows + 1

    return np.array(matrix)

print(random_matrix(range(10), 5))
#make sure you understand the function random.sample

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

These are different Form content types defined by W3C. If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work. This is the default.

But if you have to send non-ASCII text or large binary data, the form-data is for that.

You can use Raw if you want to send plain text or JSON or any other kind of string. Like the name suggests, Postman sends your raw string data as it is without modifications. The type of data that you are sending can be set by using the content-type header from the drop down.

Binary can be used when you want to attach non-textual data to the request, e.g. a video/audio file, images, or any other binary data file.

Refer to this link for further reading: Forms in HTML documents

Display animated GIF in iOS

#import <QuickLook/QuickLook.h>
#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    QLPreviewController *preview = [[QLPreviewController alloc] init];
    preview.dataSource = self;

    [self addChildViewController:preview];
    [self.view addSubview:preview.view];
}

#pragma mark - QLPreviewControllerDataSource

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController
{
    return 1;
}

- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx
{
    NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myanimated.gif" ofType:nil]];
    return fileURL;
}

@end

Open multiple Projects/Folders in Visual Studio Code

If you are using unix like OS, you can create a soft link to your target folder.

E.g. I want to see golang source while I am using VSCode. So, I create a soft link to go/src under my project folder.

ln -s /usr/local/go/src gosrc

Hope this helps!


Update: 11/28, 2017

Multi Root Workspaces[0] landed in the stable build, finally. https://code.visualstudio.com/updates/v1_18#_support-for-multi-root-workspaces

[0] https://github.com/Microsoft/vscode/issues/396

How to download file in swift?

Example downloader class without Alamofire:

class Downloader {
    class func load(URL: NSURL) {
        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let request = NSMutableURLRequest(URL: URL)
        request.HTTPMethod = "GET"
        let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            if (error == nil) {
                // Success
                let statusCode = (response as NSHTTPURLResponse).statusCode
                println("Success: \(statusCode)")

                // This is your file-variable:
                // data
            }
            else {
                // Failure
                println("Failure: %@", error.localizedDescription);
            }
        })
        task.resume()
    }
}

This is how to use it in your own code:

class Foo {
    func bar() {
        if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
            Downloader.load(URL)
        }
    }
}

Swift 3 Version

Also note to download large files on disk instead instead in memory. see `downloadTask:

class Downloader {
    class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
        let request = try! URLRequest(url: url, method: .get)

        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Success: \(statusCode)")
                }

                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
                    completion()
                } catch (let writeError) {
                    print("error writing file \(localUrl) : \(writeError)")
                }

            } else {
                print("Failure: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }
}

How to get GET (query string) variables in Express.js on Node.js?

I learned from the other answers and decided to use this code throughout my site:

var query = require('url').parse(req.url,true).query;

Then you can just call

var id = query.id;
var option = query.option;

where the URL for get should be

/path/filename?id=123&option=456

Redirect on select option in select box

Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.

Here's an example:

https://jsfiddle.net/bL5sq/

_x000D_
_x000D_
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">_x000D_
  <option value="">Select...</option>_x000D_
  <option value="https://google.com">Google</option>_x000D_
  <option value="https://yahoo.com">Yahoo</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to turn NaN from parseInt into 0 for an empty string?

Do a separate check for an empty string ( as it is one specific case ) and set it to zero in this case.

You could appeand "0" to the start, but then you need to add a prefix to indicate that it is a decimal and not an octal number

Get all column names of a DataTable into string array using (LINQ/Predicate)

List<String> lsColumns = new List<string>();

if(dt.Rows.Count>0)
{
    var count = dt.Rows[0].Table.Columns.Count;

    for (int i = 0; i < count;i++ )
    {
        lsColumns.Add(Convert.ToString(dt.Rows[0][i]));
    }
}

Solution to "subquery returns more than 1 row" error

= can be used when the subquery returns only 1 value.

When subquery returns more than 1 value, you will have to use IN:

select * 
from table
where id IN (multiple row query);

For example:

SELECT *
FROM Students
WHERE Marks = (SELECT MAX(Marks) FROM Students)   --Subquery returns only 1 value

SELECT *
FROM Students
WHERE Marks IN 
      (SELECT Marks 
       FROM Students 
       ORDER BY Marks DESC
       LIMIT 10)                       --Subquery returns 10 values

How can I create a copy of an Oracle table without copying the data?

Create table target_table 
As
Select * 
from source_table 
where 1=2;

Source_table is the table u wanna copy the structure of.

openCV video saving in python

import cv2

cap = cv2.VideoCapture(0)

fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

out = cv2.VideoWriter('output.mp4', fourcc, 20,(frame_width,frame_height),True )
print(int(cap.get(3)))
print(int(cap.get(4)))
while(cap.isOpened()):
    ret,frame = cap.read()
    if ret == True:
        print(frame.shape)
        out.write(frame)
        cv2.imshow('Frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()`enter code here`

cv2.destroyAllWindows()

This works fine but the problem of having video size relatively very small means nothing is captured. So make sure the height and width of a video and the image that you are going to recorded is same. If you are using some manipulation after capturing a video than you must confirm the size (before and after). Hope it will save some1's hour

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Why not create a class Book with properties: Number, Title, and Price. Then store them in a single dimensional array? That way instead of calling

Book[i][j] 

..to get your books title, call

Book[i].Title

Seems to me like it would be a bit more manageable and code friendly.

Class Diagrams in VS 2017

the following procedure worked for me:

  • Close VS.
  • Run Visual Studio Installer.
  • Click on the 'Modify' button under 'Visual Studio Professional 2017'
  • In the new window, scroll down and select 'Visual Studio Extension Development' under 'Other Toolsets'.
  • Then on the right, if not selected yet, click on 'Class Designer'
  • Click on 'Modify' to confirm

Assign output of a program to a variable using a MS batch file

Some macros to set the output of a command to a variable/

For directly in the command prompt

c:\>doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"

c:\>assign WHOAMI /LOGONID,my-id

c:\>echo %my-id%

Macro with arguments

As this macro accepts arguments as a function i think it is the neatest macro to be used in a batch file:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

FOR /F macro

not so easy to read as the previous macro.

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Macro using a temp file

Easier to read , it is not so slow if you have a SSD drive but still it creates a temp file.

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

Append text to textarea with javascript

Give this a try:

<!DOCTYPE html>
<html>
<head>
    <title>List Test</title>
    <style>
        li:hover {
            cursor: hand; cursor: pointer;
        }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                $('#alltext').append($(this).text());
            });
        });
    </script>
</head>
<body>

    <h2>List items</h2>
    <ol>
        <li>Hello</li>
        <li>World</li>
        <li>Earthlings</li>
    </ol>
    <form>
        <textarea id="alltext"></textarea>
    </form>

</body>
</html>

Error:(1, 0) Plugin with id 'com.android.application' not found

For future reference: For me, this issue was solely caused by the fact that I wasn't running Android Studio as administrator. I had the shortcut on Windows configured to always run as administrator, but after reinstalling Android Studio, the shortcut was replaced, and so it ran without administrator rights. This caused a lot of opaque errors, including the one in this question.

How to open .mov format video in HTML video Tag?

You can use Controls attribute

<video id="sampleMovie" src="HTML5Sample.mov" controls></video>

C# Collection was modified; enumeration operation may not execute

Any collection that you iterate over with foreach may not be modified during iteration.

So while you're running a foreach over rankings, you cannot modify its elements, add new ones or delete any.

Select data from "show tables" MySQL query

SELECT column_comment FROM information_schema.columns WHERE table_name = 'myTable' AND column_name = 'myColumnName'

This will return the comment on: myTable.myColumnName

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

This error is caused by a line of code in /usr/share/phpmyadmin/libraries/sql.lib.php.

It seems when I installed phpMyAdmin using apt, the version in the repository (phpMyAdmin v4.6.6) is not fully compatible with PHP 7.2. There is a newer version available on the official website (v4.8 as of writing), which fixes these compatibility issues with PHP 7.2.

You can download the latest version and install it manually or wait for the repositories to update with the newer version.

Alternatively, you can make a small change to sql.lib.php to fix the error.

Firstly, backup sql.lib.php before editing.

1-interminal:

sudo cp /usr/share/phpmyadmin/libraries/sql.lib.php /usr/share/phpmyadmin/libraries/sql.lib.php.bak

2-Edit sql.lib.php. Using vi:

sudo vi /usr/share/phpmyadmin/libraries/sql.lib.php

OR Using nano:

sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php

Press CTRL + W (for nano) or ? (for vi/vim) and search for (count($analyzed_sql_results['select_expr'] == 1)

Replace it with ((count($analyzed_sql_results['select_expr']) == 1)

Save file and exit. (Press CTRL + X, press Y and then press ENTER for nano users / (for vi/vim) hit ESC then type :wq and press ENTER)

Detect if value is number in MySQL

you can do using CAST

  SELECT * from tbl where col1 = concat(cast(col1 as decimal), "")

What does `ValueError: cannot reindex from a duplicate axis` mean?

I got this error when I tried adding a column from a different table. Indeed I got duplicate index values along the way. But it turned out I was just doing it wrong: I actually needed to df.join the other table.

This pointer might help someone in a similar situation.

Is it possible to get the current spark context settings in PySpark?

Simply running

sc.getConf().getAll()

should give you a list with all settings.

ImportError: No module named dateutil.parser

For Python 3 above, use:

sudo apt-get install python3-dateutil

Serving static web resources in Spring Boot & Spring Security application

  @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/resources/**"); // #3
      }

Ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.

Partly cherry-picking a commit with Git

Assuming the changes you want are at the head of the branch you want the changes from, use git checkout

for a single file :

git checkout branch_that_has_the_changes_you_want path/to/file.rb

for multiple files just daisy chain :

git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb

Android 6.0 multiple permissions

Checking every situation

if denied - showing Alert dialog to user why we need permission

public static final int MULTIPLE_PERMISSIONS = 1;
public static final int CAMERA_PERMISSION_REQUEST_CODE = 2;
public static final int STORAGE_PERMISSION_REQUEST_CODE = 3;

    private void askPermissions() {

    int permissionCheckStorage = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    int permissionCheckCamera = ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA); 

   // we already asked for permisson & Permission granted, call camera intent
    if (permissionCheckStorage == PackageManager.PERMISSION_GRANTED && permissionCheckCamera == PackageManager.PERMISSION_GRANTED) {

        launchCamera();

    } //asking permission for the first time
     else if (permissionCheckStorage != PackageManager.PERMISSION_GRANTED && permissionCheckCamera != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MULTIPLE_PERMISSIONS);

    } else {
        // Permission denied, so request permission

        // if camera request is denied
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("You need to give permission to take pictures in order to work this feature.");
            builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.setPositiveButton("GIVE PERMISSION", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();

                    // Show permission request popup
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            CAMERA_PERMISSION_REQUEST_CODE);
                }
            });
            builder.show();

        }   // if storage request is denied
                else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("You need to give permission to access storage in order to work this feature.");
            builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.setPositiveButton("GIVE PERMISSION", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();

                    // Show permission request popup
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            STORAGE_PERMISSION_REQUEST_CODE);
                }
            });
            builder.show();

        } 

    }
}

Checking Permission Results

 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.CAMERA)) {
                // check whether camera permission granted or not.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    launchCamera();
                }
            }
            break;
        case STORAGE_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // check whether storage permission granted or not.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    launchCamera();
                }
            }
            break;
        case MULTIPLE_PERMISSIONS:
            if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.CAMERA) && permissions[1].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // check whether All permission granted or not.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    launchCamera();

                }
            }
            break;
        default:
            break;
    }
}

you can just copy and paste this code, it works fine. change context(this) & permissions according to you.

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

A slight variation on the above simplified approach.

var result = yyy.Distinct().Count() == yyy.Count();

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Download system image(of targeted android level of your project) from sdk manager for the project you have imported.

This error comes when you do not have target sdk of your android project installed in sdk folder

for eg. Your imported project's target sdk level may be android-19 and on sdk folder->system-images you may have android-21 installed. so you have to download android-19 system image and other files from sdk manager or you can copy paste it if you have the system image.

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

This takes the last. Not the maximum though:

In [10]: df.drop_duplicates(subset='A', keep="last")
Out[10]: 
   A   B
1  1  20
3  2  40
4  3  10

You can do also something like:

In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.loc[x.B.idxmax()])
Out[12]: 
   A   B
A       
1  1  20
2  2  40
3  3  10

Change Tomcat Server's timeout in Eclipse

double click tomcat , see configure setting with "timeout" modify the number. Maybe this not the tomcat error.U can see the DB connection is achievable.

SSH to Vagrant box in Windows?

Now I have a much better solution that enables painless Vagrant upgrade. It is based on patched file.

The first line of a vagrantfile should be:

load "vagrantfile_ssh" if Vagrant::Util::Platform.windows?

And the patched vagrantfile_ssh file (originaly named ssh.rb) should exist in the same directory as vagrantfile. This is both elegant and functional.

Download the patched vagrantfile_ssh.

Type safety: Unchecked cast

As the messages above indicate, the List cannot be differentiated between a List<Object> and a List<String> or List<Integer>.

I've solved this error message for a similar problem:

List<String> strList = (List<String>) someFunction();
String s = strList.get(0);

with the following:

List<?> strList = (List<?>) someFunction();
String s = (String) strList.get(0);

Explanation: The first type conversion verifies that the object is a List without caring about the types held within (since we cannot verify the internal types at the List level). The second conversion is now required because the compiler only knows the List contains some sort of objects. This verifies the type of each object in the List as it is accessed.

How to validate IP address in Python?

The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.

>>> from IPy import IP
>>> IP('127.0.0.1')
IP('127.0.0.1')
>>> IP('277.0.0.1')
Traceback (most recent call last):
 ...
ValueError: '277.0.0.1': single byte must be 0 <= byte < 256
>>> IP('foobar')
Traceback (most recent call last):
 ...
ValueError: invalid literal for long() with base 10: 'foobar'

However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.

If you're using Python 3.3 or later, it now includes the ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('277.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'foobar' does not appear to be an IPv4 or IPv6 address

For Python 2, you can get the same functionality using ipaddress if you install python-ipaddress:

pip install ipaddress

This module is compatible with Python 2 and provides a very similar API to that of the ipaddress module included in the Python Standard Library since Python 3.3. More details here. In Python 2 you will need to explicitly convert the IP address string to unicode: ipaddress.ip_address(u'127.0.0.1').

How to position a div in bottom right corner of a browser?

Try this:

#foo
{
    position: absolute;
    top: 100%;
    right: 0%;
}

Why does Firebug say toFixed() is not a function?

In a function, use as

render: function (args) {
    if (args.value != 0)
        return (parseFloat(args.value).toFixed(2));


},

Need table of key codes for android and presenter

List Of Key codes:

a - z-> 29 - 54

"0" - "9"-> 7 - 16

BACK BUTTON - 4, MENU BUTTON - 82

UP-19, DOWN-20, LEFT-21, RIGHT-22

SELECT (MIDDLE) BUTTON - 23

SPACE - 62, SHIFT - 59, ENTER - 66, BACKSPACE - 67

Which JDK version (Language Level) is required for Android Studio?

Answer Clarification - Android Studio supports JDK8

The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.

Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).


Java 8 update (3/19/14)

Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.

Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/

If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising.

Another Update: Android added Java 7 support

Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Older response

I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.

enter image description here

What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.

enter image description here


Update: See this SO post -- https://stackoverflow.com/a/9567402/413254

Converting char[] to byte[]

Convert without creating String object:

import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.util.Arrays;

byte[] toBytes(char[] chars) {
  CharBuffer charBuffer = CharBuffer.wrap(chars);
  ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
  byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
            byteBuffer.position(), byteBuffer.limit());
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
  return bytes;
}

Usage:

char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
byte[] bytes = toBytes(chars);
/* do something with chars/bytes */
Arrays.fill(chars, '\u0000'); // clear sensitive data
Arrays.fill(bytes, (byte) 0); // clear sensitive data

Solution is inspired from Swing recommendation to store passwords in char[]. (See Why is char[] preferred over String for passwords?)

Remember not to write sensitive data to logs and ensure that JVM won't hold any references to it.


The code above is correct but not effective. If you don't need performance but want security you can use it. If security also not a goal then do simply String.getBytes. Code above is not effective if you look down of implementation of encode in JDK. Besides you need to copy arrays and create buffers. Another way to convert is inline all code behind encode (example for UTF-8):

val xs: Array[Char] = "A ß € ?  ".toArray
val len = xs.length
val ys: Array[Byte] = new Array(3 * len) // worst case
var i = 0; var j = 0 // i for chars; j for bytes
while (i < len) { // fill ys with bytes
  val c = xs(i)
  if (c < 0x80) {
    ys(j) = c.toByte
    i = i + 1
    j = j + 1
  } else if (c < 0x800) {
    ys(j) = (0xc0 | (c >> 6)).toByte
    ys(j + 1) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 2
  } else if (Character.isHighSurrogate(c)) {
    if (len - i < 2) throw new Exception("overflow")
    val d = xs(i + 1)
    val uc: Int = 
      if (Character.isLowSurrogate(d)) {
        Character.toCodePoint(c, d)
      } else {
        throw new Exception("malformed")
      }
    ys(j) = (0xf0 | ((uc >> 18))).toByte
    ys(j + 1) = (0x80 | ((uc >> 12) & 0x3f)).toByte
    ys(j + 2) = (0x80 | ((uc >>  6) & 0x3f)).toByte
    ys(j + 3) = (0x80 | (uc & 0x3f)).toByte
    i = i + 2 // 2 chars
    j = j + 4
  } else if (Character.isLowSurrogate(c)) {
    throw new Exception("malformed")
  } else {
    ys(j) = (0xe0 | (c >> 12)).toByte
    ys(j + 1) = (0x80 | ((c >> 6) & 0x3f)).toByte
    ys(j + 2) = (0x80 | (c & 0x3f)).toByte
    i = i + 1
    j = j + 3
  }
}
// check
println(new String(ys, 0, j, "UTF-8"))

Excuse me for using Scala language. If you have problems with converting this code to Java I can rewrite it. What about performance always check on real data (with JMH for example). This code looks very similar to what you can see in JDK[2] and Protobuf[3].

How do I check to see if a value is an integer in MySQL?

What about:

WHERE table.field = "0" or CAST(table.field as SIGNED) != 0

to test for numeric and the corrolary:

WHERE table.field != "0" and CAST(table.field as SIGNED) = 0

How can I pair socks from a pile efficiently?

When I sort socks, I do an approximate radix sort, dropping socks near other socks of the same colour/pattern type. Except in the case when I can see an exact match at/near the location I'm about to drop the sock I extract the pair at that point.

Almost all the other algorithms (including the top scoring answer by usr) sort, then remove pairs. I find that, as a human, it is better to minimize the number of socks being considered at one time.

I do this by:

  1. Picking a distinctive sock (whatever catches my eye first in the pile).
  2. Starting a radix sort from that conceptual location by pulling socks from the pile based on similarity to that one.
  3. Place the new sock near into the current pile, with a distance based on how different it is. If you find yourself putting the sock on top of another because it is identical, form the pair there, and remove them. This means that future comparisons take less effort to find the correct place.

This takes advantage of the human ability to fuzzy-match in O(1) time, which is somewhat equivalent to the establishment of a hash-map on a computing device.

By pulling the distinctive socks first, you leave space to "zoom" in on the features which are less distinctive, to begin with.

After eliminating the fluro coloured, the socks with stripes, and the three pairs of long socks, you might end up with mostly white socks roughly sorted by how worn they are.

At some point, the differences between socks are small enough that other people won't notice the difference, and any further matching effort is not needed.

Set active tab style with AngularJS

Came here for solution .. though above solutions are working fine but found them little bit complex unnecessary. For people who still looking for a easy and neat solution, it will do the task perfectly.

<section ng-init="tab=1">
                <ul class="nav nav-tabs">
                    <li ng-class="{active: tab == 1}"><a ng-click="tab=1" href="#showitem">View Inventory</a></li>
                    <li ng-class="{active: tab == 2}"><a ng-click="tab=2" href="#additem">Add new item</a></li>
                    <li ng-class="{active: tab == 3}"><a ng-click="tab=3" href="#solditem">Sold item</a></li>
                </ul>
            </section>

Change grid interval and specify tick labels in Matplotlib

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid
ax.grid(which='both')

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

plt.show()

Output is this:

result

change values in array when doing foreach

With the Array object methods you can modify the Array content yet compared to the basic for loops, these methods lack one important functionality. You can not modify the index on the run.

For example if you will remove the current element and place it to another index position within the same array you can easily do this. If you move the current element to a previous position there is no problem in the next iteration you will get the same next item as if you hadn't done anything.

Consider this code where we move the item at index position 5 to index position 2 once the index counts up to 5.

var ar = [0,1,2,3,4,5,6,7,8,9];
ar.forEach((e,i,a) => {
i == 5 && a.splice(2,0,a.splice(i,1)[0])
console.log(i,e);
}); // 0 0 - 1 1 - 2 2 - 3 3 - 4 4 - 5 5 - 6 6 - 7 7 - 8 8 - 9 9

However if we move the current element to somewhere beyond the current index position things get a little messy. Then the very next item will shift into the moved items position and in the next iteration we will not be able to see or evaluate it.

Consider this code where we move the item at index position 5 to index position 7 once the index counts up to 5.

var a = [0,1,2,3,4,5,6,7,8,9];
a.forEach((e,i,a) => {
i == 5 && a.splice(7,0,a.splice(i,1)[0])
console.log(i,e);
}); // 0 0 - 1 1 - 2 2 - 3 3 - 4 4 - 5 5 - 6 7 - 7 5 - 8 8 - 9 9

So we have never met 6 in the loop. Normally in a for loop you are expected decrement the index value when you move the array item forward so that your index stays at the same position in the next run and you can still evaluate the item shifted into the removed item's place. This is not possible with array methods. You can not alter the index. Check the following code

var a = [0,1,2,3,4,5,6,7,8,9];
a.forEach((e,i,a) => {
i == 5 && (a.splice(7,0,a.splice(i,1)[0]), i--);
console.log(i,e);
}); // 0 0 - 1 1 - 2 2 - 3 3 - 4 4 - 4 5 - 6 7 - 7 5 - 8 8 - 9 9

As you see when we decrement i it will not continue from 5 but 6, from where it was left.

So keep this in mind.

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

How do I remove the title bar from my app?

  1. open styles.xml
  2. insert
 <style name="no_title" parent="AppTheme">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowContentOverlay">@null</item>
 </style>

you can change name="---------"

  1. open Androidmaifest.xm

    find android:theme="@style/AppTheme" chang to android:theme="@style/no_title"

  2. click select Theme on menubar (it's green color near MainActivity)

    • click project Theme
    • click no_title (on you right hand Side)
    • click OK

When to use IList and when to use List

You are most often better of using the most general usable type, in this case the IList or even better the IEnumerable interface, so that you can switch the implementation conveniently at a later time.

However, in .NET 2.0, there is an annoying thing - IList does not have a Sort() method. You can use a supplied adapter instead:

ArrayList.Adapter(list).Sort()

How does strtok() split the string into tokens in C?

To understand how strtok() works, one first need to know what a static variable is. This link explains it quite well....

The key to the operation of strtok() is preserving the location of the last seperator between seccessive calls (that's why strtok() continues to parse the very original string that is passed to it when it is invoked with a null pointer in successive calls)..

Have a look at my own strtok() implementation, called zStrtok(), which has a sligtly different functionality than the one provided by strtok()

char *zStrtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;           /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

And here is an example usage

  Example Usage
      char str[] = "A,B,,,C";
      printf("1 %s\n",zStrtok(s,","));
      printf("2 %s\n",zStrtok(NULL,","));
      printf("3 %s\n",zStrtok(NULL,","));
      printf("4 %s\n",zStrtok(NULL,","));
      printf("5 %s\n",zStrtok(NULL,","));
      printf("6 %s\n",zStrtok(NULL,","));

  Example Output
      1 A
      2 B
      3 ,
      4 ,
      5 C
      6 (null)

The code is from a string processing library I maintain on Github, called zString. Have a look at the code, or even contribute :) https://github.com/fnoyanisi/zString

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

What does 'super' do in Python?

Doesn't all of this assume that the base class is a new-style class?

class A:
    def __init__(self):
        print("A.__init__()")

class B(A):
    def __init__(self):
        print("B.__init__()")
        super(B, self).__init__()

Will not work in Python 2. class A must be new-style, i.e: class A(object)

Java ArrayList how to add elements at the beginning

Using Specific Datastructures

There are various data structures which are optimized for adding elements at the first index. Mind though, that if you convert your collection to one of these, the conversation will probably need a time and space complexity of O(n)

Deque

The JDK includes the Deque structure which offers methods like addFirst(e) and offerFirst(e)

Deque<String> deque = new LinkedList<>();
deque.add("two");
deque.add("one");
deque.addFirst("three");
//prints "three", "two", "one"

Analysis

Space and time complexity of insertion is with LinkedList constant (O(1)). See the Big-O cheatsheet.

Reversing the List

A very easy but inefficient method is to use reverse:

 Collections.reverse(list);
 list.add(elementForTop);
 Collections.reverse(list);

If you use Java 8 streams, this answer might interest you.

Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Looking at the JDK implementation this has a O(n) time complexity so only suitable for very small lists.

Send POST data via raw json with postman

I was facing the same problem, following code worked for me:

$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

How to increment variable under DOS?

Directly from the command line:

 for /L %n in (1,1,100) do @echo %n

Using a batch file:

 @echo off
 for /L %%n in (1,1,100) do echo %%n

Displays:

 1
 2
 3
 ...
 100

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Use cell's color as condition in if statement (function)

Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).

In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

SQL query for extracting year from a date

SELECT date_column_name FROM table_name WHERE EXTRACT(YEAR FROM date_column_name) = 2020

R: Comment out block of code

Most of the editors take some kind of shortcut to comment out blocks of code. The default editors use something like command or control and single quote to comment out selected lines of code. In RStudio it's Command or Control+/. Check in your editor.

It's still commenting line by line, but they also uncomment selected lines as well. For the Mac RGUI it's command-option ' (I'm imagining windows is control option). For Rstudio it's just Command or Control + Shift + C again.

These shortcuts will likely change over time as editors get updated and different software becomes the most popular R editors. You'll have to look it up for whatever software you have.

UITapGestureRecognizer - single tap and double tap

Not sure if that's exactly what are you looking for, but I did single/double taps without gesture recognizers. I'm using it in a UITableView, so I used that code in the didSelectRowAtIndexPath method

    tapCount++;
    switch (tapCount)
    {
        case 1: //single tap
            [self performSelector:@selector(singleTap:) withObject: indexPath afterDelay: 0.2];
            break;
        case 2: //double tap
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTap:) object:indexPath];
            [self performSelector:@selector(doubleTap:) withObject: indexPath];
            break;
        default:
            break;
    }
    if (tapCount>2) tapCount=0;

Methods singleTap and doubleTap are just void with NSIndexPath as a parameter:

- (void)singleTap:(NSIndexPath *)indexPath {
  //do your stuff for a single tap
}

- (void)doubleTap:(NSIndexPath *)indexPath {
  //do your stuff for a double tap
}

Hope it helps

Can you create nested WITH clauses for Common Table Expressions?

I was trying to measure the time between events with the exception of what one entry that has multiple processes between the start and end. I needed this in the context of other single line processes.

I used a select with an inner join as my select statement within the Nth cte. The second cte I needed to extract the start date on X and end date on Y and used 1 as an id value to left join to put them on a single line.

Works for me, hope this helps.

cte_extract
as 
(
    select ps.Process as ProcessEvent
        , ps.ProcessStartDate 
        , ps.ProcessEndDate 
        -- select strt.*
    from dbo.tbl_some_table ps 
    inner join (select max(ProcessStatusId) ProcessStatusId 
                    from dbo.tbl_some_table 
                where Process = 'some_extract_tbl' 
                and convert(varchar(10), ProcessStartDate, 112) < '29991231'
                ) strt on strt.ProcessStatusId = ps.ProcessStatusID
), 
cte_rls
as 
(
    select 'Sample' as ProcessEvent, 
     x.ProcessStartDate, y.ProcessEndDate  from (
    select 1 as Id, ps.Process as ProcessEvent
        , ps.ProcessStartDate 
        , ps.ProcessEndDate
        -- select strt.*
    from dbo.tbl_some_table ps 
    inner join (select max(ProcessStatusId) ProcessStatusId 
                    from dbo.tbl_some_table 
                where Process = 'XX Prcss' 
                and convert(varchar(10), ProcessStartDate, 112) < '29991231'
                ) strt on strt.ProcessStatusId = ps.ProcessStatusID
    ) x
    left join (
        select 1 as Id, ps.Process as ProcessEvent
            , ps.ProcessStartDate 
            , ps.ProcessEndDate
            -- select strt.*
        from dbo.tbl_some_table ps 
        inner join (select max(ProcessStatusId) ProcessStatusId
                    from dbo.tbl_some_table 
                    where Process = 'YY Prcss Cmpltd' 
                    and convert(varchar(10), ProcessEndDate, 112) < '29991231'
                    ) enddt on enddt.ProcessStatusId = ps.ProcessStatusID
            ) y on y.Id = x.Id 
),

.... other ctes

How to read file from relative path in Java project? java.io.File cannot find the path specified

InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
} catch (Exception e) {
    e.printStackTrace();
}

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

How to exit a function in bash

Use:

return [n]

From help return

return: return [n]

Return from a shell function.

Causes a function or sourced script to exit with the return value
specified by N.  If N is omitted, the return status is that of the
last command executed within the function or script.

Exit Status:
Returns N, or failure if the shell is not executing a function or script.