Programs & Examples On #Check constraints

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

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

WITH CHECK is indeed the default behaviour however it is good practice to include within your coding.

The alternative behaviour is of course to use WITH NOCHECK, so it is good to explicitly define your intentions. This is often used when you are playing with/modifying/switching inline partitions.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

Before answering, let's add some background, explaining what this HEAD is.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time (excluding git worktree).

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history it's called detached HEAD.

Enter image description here

On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch:

Enter image description here

Enter image description here


A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits to go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

Enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7) you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there, reset && checkout modify the HEAD.

Enter image description here

How to find the parent element using javascript

Using plain javascript:

element.parentNode

In jQuery:

element.parent()

How do I query using fields inside the new PostgreSQL JSON datatype?

With Postgres 9.3+, just use the -> operator. For example,

SELECT data->'images'->'thumbnail'->'url' AS thumb FROM instagram;

see http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/ for some nice examples and a tutorial.

Hash table in JavaScript

You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.

Check if year is leap year in javascript

You can try using JavaScript's Date Object

new Date(year,month).getFullYear()%4==0

This will return true or false.

Replace negative values in an numpy array

Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.

>>> a = [1, 2, 3, -4, 5]

>>> def zero_if_negative(x):
...   if x < 0:
...     return 0
...   return x
...

>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]

>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]

How to get folder directory from HTML input type "file" or any other way?

Stumbled on this page as well, and then found out this is possible with just javascript (no plugins like ActiveX or Flash), but just in chrome:

https://plus.google.com/+AddyOsmani/posts/Dk5UhZ6zfF3

Basically, they added support for a new attribute on the file input element "webkitdirectory". You can use it like this:

<input type="file" id="ctrl" webkitdirectory directory multiple/>

It allows you to select directories. The multiple attribute is a good fallback for browsers that support multiple file selection but not directory selection.

When you select a directory the files are available through the dom object for the control (document.getElementById('ctrl')), just like they are with the multiple attribute. The browsers adds all files in the selected directory to that list recursively.

You can already add the directory attribute as well in case this gets standardized at some point (couldn't find any info regarding that)

jQuery selector for the label of a checkbox

This should do it:

$("label[for=comedyclubs]")

If you have non alphanumeric characters in your id then you must surround the attr value with quotes:

$("label[for='comedy-clubs']")

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

How to rsync only a specific list of files?

--files-from= parameter needs trailing slash if you want to keep the absolute path intact. So your command would become something like below:

rsync -av --files-from=/path/to/file / /tmp/

This could be done like there are a large number of files and you want to copy all files to x path. So you would find the files and throw output to a file like below:

find /var/* -name *.log > file

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

jQuery: Uncheck other checkbox on one checked

I think the prop method is more convenient when it comes to boolean attribute. http://api.jquery.com/prop/

Node.js: get path from the request

simply call req.url. that should do the work. you'll get something like /something?bla=foo

How to format dateTime in django template?

I suspect wpis.entry.lastChangeDate has been somehow transformed into a string in the view, before arriving to the template.

In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper, and then see if the template crashes.

You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.

On an unrelated notice, why don't you use models.DateTimeField(auto_now_add=True) to set the datetime on creation?

How to inspect FormData?

Here's a function to log entries of a FormData object to the console as an object.

export const logFormData = (formData) => {
    const entries = formData.entries();
    const result = {};
    let next;
    let pair;
    while ((next = entries.next()) && next.done === false) {
        pair = next.value;
        result[pair[0]] = pair[1];
    }
    console.log(result);
};

MDN doc on .entries()

MDN doc on .next() and .done

Shadow Effect for a Text in Android?

put these in values/colors.xml

<resources>
    <color name="light_font">#FBFBFB</color>
    <color name="grey_font">#ff9e9e9e</color>
    <color name="text_shadow">#7F000000</color>
    <color name="text_shadow_white">#FFFFFF</color>
</resources>

Then in your layout xml here are some example TextView's

Example of Floating text on Light with Dark shadow

<TextView android:id="@+id/txt_example1"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textSize="14sp"
                  android:textStyle="bold"
                  android:textColor="@color/light_font"
                  android:shadowColor="@color/text_shadow"
                  android:shadowDx="1"
                  android:shadowDy="1"
                  android:shadowRadius="2" />

enter image description here

Example of Etched text on Light with Dark shadow

<TextView android:id="@+id/txt_example2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/light_font"
                android:shadowColor="@color/text_shadow"
                android:shadowDx="-1"
                android:shadowDy="-1"
                android:shadowRadius="1" />

enter image description here

Example of Crisp text on Light with Dark shadow

<TextView android:id="@+id/txt_example3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14sp"
                android:textStyle="bold"
                android:textColor="@color/grey_font"
                android:shadowColor="@color/text_shadow_white"
                android:shadowDx="-2"
                android:shadowDy="-2"
                android:shadowRadius="1" />

enter image description here

Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.

How to select the nth row in a SQL database table?

SELECT
    top 1 *
FROM
    table_name
WHERE
    column_name IN (
        SELECT
            top N column_name
        FROM
            TABLE
        ORDER BY
            column_name
    )
ORDER BY
    column_name DESC

I've written this query for finding Nth row. Example with this query would be

SELECT
    top 1 *
FROM
    Employee
WHERE
    emp_id IN (
        SELECT
            top 7 emp_id
        FROM
            Employee
        ORDER BY
            emp_id
    )
ORDER BY
    emp_id DESC

What are the alternatives now that the Google web search API has been deprecated?

You could just send them through like a browser does, and then parse the html, that is what I have always done, even for things like Youtube.

Expression must be a modifiable lvalue

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

Bootstrap 4 responsive tables won't take up 100% width

For Bootstrap 4.x use display utilities:

w-100 d-print-block d-print-table

Usage:

<table class="table w-100 d-print-block d-print-table">

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

Really fast comparison, to get count of differences. Using specific column name.

colname = "CreatedDate" # specify column name
index <- match(colname, names(source_df)) # get index name for column name
sel <- source_df[, index] == target_df[, index] # get differences, gives you dataframe with TRUE and FALSE values
table(sel)["FALSE"] # count of differences
table(sel)["TRUE"] # count of matches

For complete dataframe, do not provide column or index name

sel <- source_df[, ] == target_df[, ] # gives you dataframe with TRUE and FALSE values
table(sel)["FALSE"] # count of differences
table(sel)["TRUE"] # count of matches

Fastest way to add an Item to an Array

For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.

Module ArrayExtension
    <Extension()> _
    Public Sub Add(Of T)(ByRef arr As T(), item As T)
        If arr IsNot Nothing Then
            Array.Resize(arr, arr.Length + 1)
            arr(arr.Length - 1) = item
        Else
            ReDim arr(0)
            arr(0) = item
        End If

    End Sub
End Module

How to show text on image when hovering?

This is what I use to make the text appear on hover:

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
div {_x000D_
  position: relative;_x000D_
  top: 0px;_x000D_
  left: 0px;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border-radius: 50%;_x000D_
  overflow: hidden;_x000D_
  text-align: center_x000D_
}_x000D_
_x000D_
img {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: absolute;_x000D_
  border-radius: 50%_x000D_
}_x000D_
_x000D_
img:hover {_x000D_
  opacity: 0;_x000D_
  transition:opacity 2s;_x000D_
}_x000D_
_x000D_
heading {_x000D_
  line-height: 40px;_x000D_
  font-weight: bold;_x000D_
  font-family: "Trebuchet MS";_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  display: block_x000D_
}_x000D_
_x000D_
div p {_x000D_
  z-index: -1;_x000D_
  width: 420px;_x000D_
  line-height: 20px;_x000D_
  display: inline-block;_x000D_
  padding: 200px 0px;_x000D_
  vertical-align: middle;_x000D_
  font-family: "Trebuchet MS";_x000D_
  height: 450px_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://68.media.tumblr.com/20b34e8d12d4230f9b362d7feb148c57/tumblr_oiwytz4dh41tf8vylo1_1280.png">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing <br>elit. Reiciendis temporibus iure dolores aspernatur excepturi <br> corporis nihil in suscipit, repudiandae. Totam._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

Regular Expression: Any character that is NOT a letter or number

This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.

\W

For example in JavaScript:

"(,,@,£,() asdf 345345".replace(/\W/g, ' '); // Output: "          asdf 345345"

Error:java: invalid source release: 8 in Intellij. What does it mean?

Lots of good answers. For those using the (almost) latest version of Intellij, at the time of writing, what can be said, is that the project JDK can be at a higher level, than that of the module. In fact without it, Maven will have to be rolled back to an older version. Therefore with the following version of Intellij: enter image description here

One should not change the project level JDK and therefore be able to leverage the Maven or Gradle settings when building, but when running Maven or running Gradle using a more modern version of the JDK. If you lower your project level JDK from say JKD8 to JDK6, Maven or Gradle will not run.

Keeping your module at a lower level JDK-wise will enable you to build it to that version, if you use the Module rebuild or build options; using the menu options for rebuilding the project will complain wit "Invalid source release:8...".

SQL how to increase or decrease one for a int column in one command

@dotjoe It is cheaper to update and check @@rowcount, do an insert after then fact.

Exceptions are expensive && updates are more frequent

Suggestion: If you want to be uber performant in your DAL, make the front end pass in a unique ID for the row to be updated, if null insert.

The DALs should be CRUD, and not need to worry about being stateless.

If you make it stateless, With good indexes, you will not see a diff with the following SQL vs 1 statement. IF (select top 1 * form x where PK=@ID) Insert else update

Route [login] not defined

Am late to the party. if your expectation is some sort of json returned other than being redirected, then edit the exception handler so do just that.

Go to go to App\Exceptions\Handler.php Then edit this code:

public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

to

public function render($request, Exception $exception)
    {
        return response()->json(
            [
                'errors' => [
                    'status' => 401,
                    'message' => 'Unauthenticated',
                ]
            ], 401
        );
    }

Draw a line in a div

_x000D_
_x000D_
$('.line').click(function() {_x000D_
  $(this).toggleClass('red');_x000D_
});
_x000D_
.line {_x000D_
  border: 0;_x000D_
  background-color: #000;_x000D_
  height: 3px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
.red {_x000D_
  background-color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<hr class="line"></hr>_x000D_
<p>click the line</p>
_x000D_
_x000D_
_x000D_

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

After struggling with all available options, I ended up writing a JWT token based SessionStore provider (the session travels inside a cookie, and no backend storage is needed).

http://www.drupalonwindows.com/en/content/token-sessionstate

Advantages:

  • Drop-in replacement, no changes to your code are needed
  • Scale better than any other centralized store, as no session storage backend is needed.
  • Faster than any other session storage, as no data needs to be retrieved from any session storage
  • Consumes no server resources for session storage.
  • Default non-blocking implementation: concurrent request won't block each other and hold a lock on the session
  • Horizontally scale your application: because the session data travels with the request itself you can have multiple web heads without worrying about session sharing.

Escaping ampersand in URL

You can rather pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.

data: "param1=getAccNos&param2="+encodeURIComponent('Dolce & Gabbana') OR
var someValue = 'Dolce & Gabbana';
data : "param1=getAccNos&param2="+encodeURIComponent(someValue)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Sending multipart/formdata with jQuery.ajax

Older versions of IE do not support FormData ( Full browser support list for FormData is here: https://developer.mozilla.org/en-US/docs/Web/API/FormData).

Either you can use a jquery plugin (For ex, http://malsup.com/jquery/form/#code-samples ) or, you can use IFrame based solution to post multipart form data through ajax: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript

Tricks to manage the available memory in an R session

Running

for (i in 1:10) 
    gc(reset = T)

from time to time also helps R to free unused but still not released memory.

Android draw a Horizontal line between views

<View
       android:id="@+id/view"
       android:layout_width="match_parent"
       android:layout_height="2dp"
       android:background="#000000" />

How to remove all callbacks from a Handler?

Define a new handler and runnable:

private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Do what ever you want
        }
    };

Call post delayed:

handler.postDelayed(runnable, sleep_time);

Remove your callback from your handler:

handler.removeCallbacks(runnable);

Log exception with traceback

Uncaught exception messages go to STDERR, so instead of implementing your logging in Python itself you could send STDERR to a file using whatever shell you're using to run your Python script. In a Bash script, you can do this with output redirection, as described in the BASH guide.

Examples

Append errors to file, other output to the terminal:

./test.py 2>> mylog.log

Overwrite file with interleaved STDOUT and STDERR output:

./test.py &> mylog.log

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Android error: Failed to install *.apk on device *: timeout

I know it sounds silly, but after trying everything recomended for this timeout issue on when running on a device, I decided to try changing the cable and it worked. It's a Coby Kyros MID7015.

Trying another cable is a good and simple option to take a chance on.

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

Understanding the map function

map isn't particularly pythonic. I would recommend using list comprehensions instead:

map(f, iterable)

is basically equivalent to:

[f(x) for x in iterable]

map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:

[(a, b) for a in iterable_a for b in iterable_b]

The syntax is a little confusing -- that's basically equivalent to:

result = []
for a in iterable_a:
    for b in iterable_b:
        result.append((a, b))

Deleting all pending tasks in celery / rabbitmq

1. To properly purge the queue of waiting tasks you have to stop all the workers (http://celery.readthedocs.io/en/latest/faq.html#i-ve-purged-messages-but-there-are-still-messages-left-in-the-queue):

$ sudo rabbitmqctl stop

or (in case RabbitMQ/message broker is managed by Supervisor):

$ sudo supervisorctl stop all

2. ...and then purge the tasks from a specific queue:

$ cd <source_dir>
$ celery amqp queue.purge <queue name>

3. Start RabbitMQ:

$ sudo rabbitmqctl start

or (in case RabbitMQ is managed by Supervisor):

$ sudo supervisorctl start all

Correct way to initialize empty slice

Empty slice and nil slice are initialized differently in Go:

var nilSlice []int 
emptySlice1 := make([]int, 0)
emptySlice2 := []int{}

fmt.Println(nilSlice == nil)    // true
fmt.Println(emptySlice1 == nil) // false
fmt.Println(emptySlice2 == nil) // false

As for all three slices, len and cap are 0.

How to get UTC time in Python?

import datetime
import pytz

# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)

# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp() 

# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000) 

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

What is a typedef enum in Objective-C?

A user defined type that has the possible values of kCircle, kRectangle, or kOblateSpheroid. The values inside the enum (kCircle, etc) are visible outside the enum, though. It's important to keep that in mind (int i = kCircle; is valid, for example).

AngularJS open modal on button click

Hope this will help you .

Here is Html code:-

    <body>
    <div ng-controller="MyController" class="container">
      <h1>Modal example</h1>
      <button ng-click="open()" class="btn btn-primary">Test Modal</button>

      <modal title="Login form" visible="showModal">
        <form role="form">

        </form>
      </modal>
    </div>
</body>

AngularJs code:-

var mymodal = angular.module('mymodal', []);

mymodal.controller('MyController', function ($scope) {
    $scope.showModal = false;
    $scope.open = function(){
    $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ title }}</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

Check this--jsfiddle

Android: upgrading DB version and adding new table

Handling database versions is very important part of application development. I assume that you already have class AppDbHelper extending SQLiteOpenHelper. When you extend it you will need to implement onCreate and onUpgrade method.

  1. When onCreate and onUpgrade methods called

    • onCreate called when app newly installed.
    • onUpgrade called when app updated.
  2. Organizing Database versions I manage versions in a class methods. Create implementation of interface Migration. E.g. For first version create MigrationV1 class, second version create MigrationV1ToV2 (these are my naming convention)


    public interface Migration {
        void run(SQLiteDatabase db);//create tables, alter tables
    }

Example migration:

public class MigrationV1ToV2 implements Migration{
      public void run(SQLiteDatabase db){
        //create new tables
        //alter existing tables(add column, add/remove constraint)
        //etc.
     }
   }
  1. Using Migration classes

onCreate: Since onCreate will be called when application freshly installed, we also need to execute all migrations(database version updates). So onCreate will looks like this:

public void onCreate(SQLiteDatabase db){
        Migration mV1=new MigrationV1();
       //put your first database schema in this class
        mV1.run(db);
        Migration mV1ToV2=new MigrationV1ToV2();
        mV1ToV2.run(db);
        //other migration if any
  }

onUpgrade: This method will be called when application is already installed and it is updated to new application version. If application contains any database changes then put all database changes in new Migration class and increment database version.

For example, lets say user has installed application which has database version 1, and now database version is updated to 2(all schema updates kept in MigrationV1ToV2). Now when application upgraded, we need to upgrade database by applying database schema changes in MigrationV1ToV2 like this:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {
        //means old version is 1
        Migration migration = new MigrationV1ToV2();
        migration.run(db);
    }
    if (oldVersion < 3) {
        //means old version is 2
    }
}

Note: All upgrades (mentioned in onUpgrade) in to database schema should be executed in onCreate

Mismatched anonymous define() module

I was also seeing the same error on browser console for a project based out of require.js. As stated under MISMATCHED ANONYMOUS DEFINE() MODULES at https://requirejs.org/docs/errors.html, this error has multiple causes, the interesting one in my case being: If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer. As it turns out, Google Closure compiler was getting used to merge/minify the Javascript code during build. Solution was to remove the Google closure compiler, and instead use require.js's optimizer (r.js) to merge the js files.

Laravel - Model Class not found

For me it was really silly I had created a ModelClass file without the .php extension. So calling that was giving model not found. So check the extension has .php

Select N random elements from a List<T> in C#

It is a lot harder than one would think. See the great Article "Shuffling" from Jeff.

I did write a very short article on that subject including C# code:
Return random subset of N elements of a given array

How can I get the assembly file version

Use this:

((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
    Assembly.GetExecutingAssembly(), 
    typeof(AssemblyFileVersionAttribute), false)
).Version;

Or this:

new Version(System.Windows.Forms.Application.ProductVersion);

Best radio-button implementation for IOS

Try UISegmentedControl. It behaves similarly to radio buttons -- presents an array of choices and lets the user pick 1.

Get number of digits with JavaScript

Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor(). Direct to the point check this out!

function digitCount ( num )
{
     return Math.floor( num.toString()).length;
}

 digitCount(2343) ;

// ES5+

 const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;

 console.log(digitCount2(3343))

Basically What's going on here. toString() and String() same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length.

Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs() in it;

Cheer You!

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

  1. In MySQL Database delete row 'profiles' from the table 'django_migrations'.
  2. Delete all migration files in migrations folder.
  3. Try again python manage.py makemigrations and python manage.py migrate command.

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Make sure that you haven't renamed some folder which falls in the path of the M2 environment variable. In case you have, then change your M2 and/or M2_HOME accordingly.

It doesn't matter whether M2 or M2_HOME are System Variable or User Variables as long as you are logged in with the same user under whose scope the environment variables are.

Generate random numbers with a given (numerical) distribution

Another answer, probably faster :)

distribution = [(1, 0.2), (2, 0.3), (3, 0.5)]  
# init distribution  
dlist = []  
sumchance = 0  
for value, chance in distribution:  
    sumchance += chance  
    dlist.append((value, sumchance))  
assert sumchance == 1.0 # not good assert because of float equality  

# get random value  
r = random.random()  
# for small distributions use lineair search  
if len(distribution) < 64: # don't know exact speed limit  
    for value, sumchance in dlist:  
        if r < sumchance:  
            return value  
else:  
    # else (not implemented) binary search algorithm  

How to remove all whitespace from a string?

Use [[:blank:]] to match any kind of horizontal white_space characters.

gsub("[[:blank:]]", "", " xx yy 11 22  33 ")
# [1] "xxyy112233"

What is the LD_PRELOAD trick?

it's easy to export mylib.so to env:

$ export LD_PRELOAD=/path/mylib.so
$ ./mybin

to disable :

$ export LD_PRELOAD=

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

Creating watermark using html and css

I would recommend everyone look into CSS grids. It has been supported by most browsers now since about 2017. Here is a link to some documentation: https://css-tricks.com/snippets/css/complete-guide-grid/ . It is so much easier to keep your page elements where you want them, especially when it comes to responsiveness. It took me all of 20 minutes to learn how to do it, and I'm a newbie!

<div class="grid-div">
    <p class="hello">Hello</p>
    <p class="world">World</p>
</div>


//begin css//

.grid-div {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-template-rows: 50% 50%;
}

.hello {
    grid-column-start: 2;
    grid-row-start: 2;
}

.world {
    grid-column-start: 1;
    grid-row-start: 2;
}

This code will split the page into 4 equal quadrants, placing the "Hello" in the bottom right, and the "World" in the bottom left without having to change their positioning or playing with margins.

This can be extrapolated into very complex grid layouts with overlapping, infinite grids of all sizes, and even grids nested inside grids, without losing control of your elements every time something changes (MS Word I'm looking at you).

Hope this helps whoever still needs it!

How to insert a SQLite record with a datetime set to 'now' in Android application?

Make sure that the field is not marked as 'not null' at the same time as you are trying to insert a default time stamp using the expression "(DATETIME('now'))"

JSON string to JS object

You can use this library from JSON.org to translate your string into a JSON object.

var var1_obj = JSON.parse(var1);

Or you can use the jquery-json library as well.

var var1_obj = $.toJSON(var1);

Best way to check for null values in Java?

As others have said #4 is the best method when not using a library method. However you should always put null on the left side of the comparison to ensure you don't accidentally assign null to foo in case of typo. In that case the compiler will catch the mistake.

// You meant to do this
if(foo != null){

// But you made a typo like this which will always evaluate to true
if(foo = null)

// Do the comparison in this way
if(null != foo)

// So if you make the mistake in this way the compiler will catch it
if(null = foo){

// obviously the typo is less obvious when doing an equality comparison but it's a good habit either way
if(foo == null){
if(foo =  null){

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Rails: Get Client IP address

I found request.env['HTTP_X_FORWARDED_FOR'] very useful too in cases when request.remote_ip returns 127.0.0.1

Reverting to a specific commit based on commit id with Git?

Do you want to roll back your repo to that state, or you just want your local repo to look like that?

If you reset --hard, it will make your local code and local history be just like it was at that commit. But if you wanted to push this to someone else who has the new history, it would fail:

git reset --hard c14809fa

And if you reset --soft, it will move your HEAD to where they were , but leave your local files etc. the same:

git reset --soft c14809fa

So what exactly do you want to do with this reset?

Edit -

You can add "tags" to your repo.. and then go back to a tag. But a tag is really just a shortcut to the sha1.

You can tag this as TAG1.. then a git reset --soft c14809fa, git reset --soft TAG1, or git reset --soft c14809fafb08b9e96ff2879999ba8c807d10fb07 would all do the same thing.

How to make Sonar ignore some classes for codeCoverage metric?

When using sonar-scanner for swift, use sonar.coverage.exclusions in your sonar-project.properties to exclude any file for only code coverage. If you want to exclude files from analysis as well, you can use sonar.exclusions. This has worked for me in swift

sonar.coverage.exclusions=**/*ViewController.swift,**/*Cell.swift,**/*View.swift

How to print variable addresses in C?

You want to use %p to print a pointer. From the spec:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

And don't forget the cast, e.g.

printf("%p\n",(void*)&a);

Label word wrapping

Change your maximum size,

label1.MaximumSize = new Size(100, 0);

And set your autosize to true.

label1.AutoSize = true;

That's it!

How to conditionally take action if FINDSTR fails to find a string

I presume you want to copy C:\OtherFolder\fileToCheck.bat to C:\MyFolder if the existing file in C:\MyFolder is either missing entirely, or if it is missing "stringToCheck".

FINDSTR sets ERRORLEVEL to 0 if the string is found, to 1 if it is not. It also sets errorlevel to 1 if the file is missing. It also prints out each line that matches. Since you are trying to use it as a condition, I presume you don't need or want to see any of the output. The 1st thing I would suggest is to redirect both the normal and error output to nul using >nul 2>&1.

Solution 1 (mostly the same as previous answers)

You can use IF ERRORRLEVEL N to check if the errorlevel is >= N. Or you can use IF NOT ERRORLEVEL N to check if errorlevel is < N. In your case you want the former.

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if errorlevel 1 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

Solution 2

You can test for a specific value of errorlevel by using %ERRORLEVEL%. You can probably check if the value is equal to 1, but it might be safer to check if the value is not equal to 0, since it is only set to 0 if the file exists and it contains the string.

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if not %errorlevel% == 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

or

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if %errorlevel% neq 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

Solution 3

There is a very compact syntax to conditionally execute a command based on the success or failure of the previous command: cmd1 && cmd2 || cmd3 which means execute cmd2 if cmd1 was successful (errorlevel=0), else execute cmd3 if cmd1 failed (errorlevel<>0). You can use && alone, or || alone. All the commands need to be on the same line. If you need to conditionally execute multiple commands you can use multiple lines by adding parentheses

cmd1 && (
   cmd2
   cmd3
) || (
   cmd4
   cmd5
)

So for your case, all you need is

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1 || xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

But beware - the || will respond to the return code of the last command executed. In my earlier pseudo code the || will obviously fire if cmd1 fails, but it will also fire if cmd1 succeeds but then cmd3 fails.

So if your success block ends with a command that may fail, then you should append a harmless command that is guaranteed to succeed. I like to use (CALL ), which is harmless, and always succeeds. It also is handy that it sets the ERRORLEVEL to 0. There is a corollary (CALL) that always fails and sets ERRORLEVEL to 1.

What is System, out, println in System.out.println() in Java

Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:

     System.out.println(data)

Simple insecure two-way data "obfuscation"?

Just thought I'd add that I've improved Mud's SimplerAES by adding a random IV that's passed back inside the encrypted string. This improves the encryption as encrypting the same string will result in a different output each time.

public class StringEncryption
{
    private readonly Random random;
    private readonly byte[] key;
    private readonly RijndaelManaged rm;
    private readonly UTF8Encoding encoder;

    public StringEncryption()
    {
        this.random = new Random();
        this.rm = new RijndaelManaged();
        this.encoder = new UTF8Encoding();
        this.key = Convert.FromBase64String("Your+Secret+Static+Encryption+Key+Goes+Here=");
    }

    public string Encrypt(string unencrypted)
    {
        var vector = new byte[16];
        this.random.NextBytes(vector);
        var cryptogram = vector.Concat(this.Encrypt(this.encoder.GetBytes(unencrypted), vector));
        return Convert.ToBase64String(cryptogram.ToArray());
    }

    public string Decrypt(string encrypted)
    {
        var cryptogram = Convert.FromBase64String(encrypted);
        if (cryptogram.Length < 17)
        {
            throw new ArgumentException("Not a valid encrypted string", "encrypted");
        }

        var vector = cryptogram.Take(16).ToArray();
        var buffer = cryptogram.Skip(16).ToArray();
        return this.encoder.GetString(this.Decrypt(buffer, vector));
    }

    private byte[] Encrypt(byte[] buffer, byte[] vector)
    {
        var encryptor = this.rm.CreateEncryptor(this.key, vector);
        return this.Transform(buffer, encryptor);
    }

    private byte[] Decrypt(byte[] buffer, byte[] vector)
    {
        var decryptor = this.rm.CreateDecryptor(this.key, vector);
        return this.Transform(buffer, decryptor);
    }

    private byte[] Transform(byte[] buffer, ICryptoTransform transform)
    {
        var stream = new MemoryStream();
        using (var cs = new CryptoStream(stream, transform, CryptoStreamMode.Write))
        {
            cs.Write(buffer, 0, buffer.Length);
        }

        return stream.ToArray();
    }
}

And bonus unit test

[Test]
public void EncryptDecrypt()
{
    // Arrange
    var subject = new StringEncryption();
    var originalString = "Testing123!£$";

    // Act
    var encryptedString1 = subject.Encrypt(originalString);
    var encryptedString2 = subject.Encrypt(originalString);
    var decryptedString1 = subject.Decrypt(encryptedString1);
    var decryptedString2 = subject.Decrypt(encryptedString2);

    // Assert
    Assert.AreEqual(originalString, decryptedString1, "Decrypted string should match original string");
    Assert.AreEqual(originalString, decryptedString2, "Decrypted string should match original string");
    Assert.AreNotEqual(originalString, encryptedString1, "Encrypted string should not match original string");
    Assert.AreNotEqual(encryptedString1, encryptedString2, "String should never be encrypted the same twice");
}

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

CryptographicException 'Keyset does not exist', but only through WCF

The Answer from Steve Sheldon fixed the problem for me, however, as I am scripting certificate permissions with out a gui, I needed a scriptable solution. I struggled to find where my private key was stored . The private key was not in -C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys , eventually I found that it was actually in C:\ProgramData\Microsoft\Crypto\Keys. Below I describe how I found that out:

I tried FindPrivateKey but it could not find the private key, and using powershell the $cert.privatekey.cspkeycontainerinfo.uniquekeycontainername was null/empty.

Luckily, certutil -store my listed the certificate and gave me the details I needed to script the solution.

================ Certificate 1 ================ Serial Number: 162f1b54fe78c7c8fa9df09 Issuer: CN=*.internal.xxxxxxx.net NotBefore: 23/08/2019 14:04 NotAfter: 23/02/2020 14:24 Subject: CN=*.xxxxxxxnet Signature matches Public Key Root Certificate: Subject matches Issuer Cert Hash(sha1): xxxxa5f0e9f0ac8b7dd634xx Key Container = {407EC7EF-8701-42BF-993F-CDEF8328DD} Unique container name: 8787033f8ccb5836115b87acb_ca96c65a-4b42-a145-eee62128a ##* ^-- filename for private key*## Provider = Microsoft Software Key Storage Provider Private key is NOT plain text exportable Encryption test passed CertUtil: -store command completed successfully.

I then scanned c\ProgramData\Microsoft\Crypto\ folder and found the file 8787033f8ccb5836115b87acb_ca96c65a-4b42-a145-eee62128a in C:\ProgramData\Microsoft\Crypto\Keys .

Giving my service account read access this file fixed the issues for me

Keeping ASP.NET Session Open / Alive

Here JQuery plugin version of Maryan solution with handle optimization. Only with JQuery 1.7+!

(function ($) {
    $.fn.heartbeat = function (options) {
        var settings = $.extend({
            // These are the defaults.
            events: 'mousemove keydown'
            , url: '/Home/KeepSessionAlive'
            , every: 5*60*1000
        }, options);

        var keepSessionAlive = false
         , $container = $(this)
         , handler = function () {
             keepSessionAlive = true;
             $container.off(settings.events, handler)
         }, reset = function () {
             keepSessionAlive = false;
             $container.on(settings.events, handler);
             setTimeout(sessionAlive, settings.every);
         }, sessionAlive = function () {
             keepSessionAlive && $.ajax({
                 type: "POST"
                 , url: settings.url
                 ,success: reset
                });
         };
        reset();

        return this;
    }
})(jQuery)

and how it does import in your *.cshtml

$('body').heartbeat(); // Simple
$('body').heartbeat({url:'@Url.Action("Home", "heartbeat")'}); // different url
$('body').heartbeat({every:6*60*1000}); // different timeout

overlay opaque div over youtube iframe

Is the opaque overlay for aesthetic purposes?

If so, you can use:

#overlay {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 50;
        background: #000;
        pointer-events: none;
        opacity: 0.8;
        color: #fff;
}

'pointer-events: none' will change the overlay behavior so that it can be physically opaque. Of course, this will only work in good browsers.

R legend placement in a plot

?legend will tell you:

Arguments

x, y
the x and y co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords: See ‘Details’.

Details:

Arguments x, y, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.

The coordinates can be specified in any way which is accepted by xy.coords. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).

The location may also be specified by setting x to a single keyword from the list bottomright, bottom, bottomleft, left, topleft, top, topright, right and center. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.

How can I get a Bootstrap column to span multiple rows?

The example below seemed to work. Just setting a height on the first element

<ul class="row">
    <li class="span4" style="height: 100px"><h1>1</h1></li>
    <li class="span4"><h1>2</h1></li>
    <li class="span4"><h1>3</h1></li>
    <li class="span4"><h1>4</h1></li>
    <li class="span4"><h1>5</h1></li>
    <li class="span4"><h1>6</h1></li>
    <li class="span4"><h1>7</h1></li>
    <li class="span4"><h1>8</h1></li>
</ul>

I can't help but thinking it's the wrong use of a row though.

How to change Java version used by TOMCAT?

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

Get MD5 hash of big files in Python

Using multiple comment/answers in this thread, here is my solution :

import hashlib
def md5_for_file(path, block_size=256*128, hr=False):
    '''
    Block size directly depends on the block size of your filesystem
    to avoid performances issues
    Here I have blocks of 4096 octets (Default NTFS)
    '''
    md5 = hashlib.md5()
    with open(path,'rb') as f: 
        for chunk in iter(lambda: f.read(block_size), b''): 
             md5.update(chunk)
    if hr:
        return md5.hexdigest()
    return md5.digest()
  • This is "pythonic"
  • This is a function
  • It avoids implicit values: always prefer explicit ones.
  • It allows (very important) performances optimizations

And finally,

- This has been built by a community, thanks all for your advices/ideas.

Resize command prompt through commands

Simply type

MODE [width],[height]

Example:

MODE 14,1

That is the smallest size possible.

MODE 1000,1000

is the largest possible, although it probably won't even fit your screen. If you want to minimize it, type

start /min [yourbatchfile/cmd]

and of course, to maximaze,

start /max [yourbatchfile/cmd]

I am currently working on doing this from the same batch files so that you don't have to have two or start it with cmd. of course, there are shortcuts, but I'm gonna try to figure it out.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

Nesting queries in SQL

If it has to be "nested", this would be one way, to get your job done:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

How to comment multiple lines in Visual Studio Code?

This is somewhat of an extension to the answer when the comment line is too long to fit on a line (above 80 chars or whatever). If the comment is too long and text needs to wrap, it's better to keep it under control (rather than use the editor's text wrap feature). This plugin Rewrap helps do just that https://marketplace.visualstudio.com/items?itemName=stkb.rewrap&ssr=false#review-details

Install the plugin in VS Code, select the text comment, comment it using one of the right methods described in the answers (Ctrl + / is easiest) and then once it's commented, press Alt + Q and this will split the text to multiple lines and also comment it. Found it pretty useful. Hope this helps someone :)

Restricting input to textbox: allowing only numbers and decimal point

<input type="text" class="number_only" />    
<script>
$(document).ready(function() {
    $('.number_only').keypress(function (event) {
        return isNumber(event, this)
    });        
});

function isNumber(evt, element) {
    var charCode = (evt.which) ? evt.which : event.keyCode

    if ((charCode != 45 || $(element).val().indexOf('-') != -1) && (charCode != 46 || $(element).val().indexOf('.') != -1) && ((charCode < 48 && charCode != 8) || charCode > 57)){
        return false;
    }
    else {
        return true;
    }
} 
</script>

http://www.encodedna.com/2013/05/enter-only-numbers-using-jquery.htm

Parsing HTTP Response in Python

You can also use python's requests library instead.

import requests

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'    
response = requests.get(url)    
dict = response.json()

Now you can manipulate the "dict" like a python dictionary.

Dropdownlist width in IE

Creating your own drop down list is more of a pain than it's worth. You can use some JavaScript to make the IE drop down work.

It uses a bit of the YUI library and a special extension for fixing IE select boxes.

You will need to include the following and wrap your <select> elements in a <span class="select-box">

Put these before the body tag of your page:

<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript">
</script>
<script src="ie-select-width-fix.js" type="text/javascript">
</script>
<script>
// for each select box you want to affect, apply this:
var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect
</script>

Post acceptance edit:

You can also do this without the YUI library and Hack control. All you really need to do is put an onmouseover="this.style.width='auto'" onmouseout="this.style.width='100px'" (or whatever you want) on the select element. The YUI control gives it that nice animation but it's not necessary. This task can also be accomplished with jquery and other libraries (although, I haven't found explicit documentation for this)

-- amendment to the edit:
IE has a problem with the onmouseout for select controls (it doesn't consider mouseover on options being a mouseover on the select). This makes using a mouseout very tricky. The first solution is the best I've found so far.

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

Python find elements in one list that are not in the other

Use a list comprehension like this:

main_list = [item for item in list_2 if item not in list_1]

Output:

>>> list_1 = ["a", "b", "c", "d", "e"]
>>> list_2 = ["a", "f", "c", "m"] 
>>> 
>>> main_list = [item for item in list_2 if item not in list_1]
>>> main_list
['f', 'm']

Edit:

Like mentioned in the comments below, with large lists, the above is not the ideal solution. When that's the case, a better option would be converting list_1 to a set first:

set_1 = set(list_1)  # this reduces the lookup time from O(n) to O(1)
main_list = [item for item in list_2 if item not in set_1]

Best way to generate a random float in C#

Here is another way that I came up with: Let's say you want to get a float between 5.5 and 7, with 3 decimals.

float myFloat;
int myInt;
System.Random rnd = new System.Random();

void GenerateFloat()
{
myInt = rnd.Next(1, 2000);
myFloat = (myInt / 1000) + 5.5f;
}

That way you will always get a bigger number than 5.5 and a smaller number than 7.

Initialising mock objects - MockIto

The other answers are great and contain more detail if you want/need them.
In addition to those, I would like to add a TL;DR:

  1. Prefer to use
    • @RunWith(MockitoJUnitRunner.class)
  2. If you cannot (because you already use a different runner), prefer to use
    • @Rule public MockitoRule rule = MockitoJUnit.rule();
  3. Similar to (2), but you should not use this anymore:
    • @Before public void initMocks() { MockitoAnnotations.initMocks(this); }
  4. If you want to use a mock in just one of the tests and don't want to expose it to other tests in the same test class, use
    • X x = mock(X.class)

(1) and (2) and (3) are mutually exclusive.
(4) can be used in combination with the others.

How do I resolve "Run-time error '429': ActiveX component can't create object"?

I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version

The import javax.persistence cannot be resolved

In newer hibernate jars, you can find the required jpa file under "hibernate-search-5.8.0.Final\dist\lib\provided\hibernate-jpa-2.1-api-1.0.0.Final". You have to add this jar file into your project java build path. This will most probably solve the issue.

How do you express binary literals in Python?

How do you express binary literals in Python?

They're not "binary" literals, but rather, "integer literals". You can express integer literals with a binary format with a 0 followed by a B or b followed by a series of zeros and ones, for example:

>>> 0b0010101010
170
>>> 0B010101
21

From the Python 3 docs, these are the ways of providing integer literals in Python:

Integer literals are described by the following lexical definitions:

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::=  "1"..."9"
digit        ::=  "0"..."9"
bindigit     ::=  "0" | "1"
octdigit     ::=  "0"..."7"
hexdigit     ::=  digit | "a"..."f" | "A"..."F"

There is no limit for the length of integer literals apart from what can be stored in available memory.

Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

Some examples of integer literals:

7     2147483647                        0o177    0b100110111
3     79228162514264337593543950336     0o377    0xdeadbeef
      100_000_000_000                   0b_1110_0101

Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.

Other ways of expressing binary:

You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):

>>> int('010101', 2)
21

You can optionally have the 0b or 0B prefix:

>>> int('0b0010101010', 2)
170

If you pass it 0 as the base, it will assume base 10 if the string doesn't specify with a prefix:

>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21

Converting from int back to human readable binary:

You can pass an integer to bin to see the string representation of a binary literal:

>>> bin(21)
'0b10101'

And you can combine bin and int to go back and forth:

>>> bin(int('010101', 2))
'0b10101'

You can use a format specification as well, if you want to have minimum width with preceding zeros:

>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'

How can I disable the default console handler, while using the java logging API?

You must instruct your logger not to send its messages on up to its parent logger:

...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...

However, this should be done before adding any more handlers to logger.

Uncaught TypeError: undefined is not a function while using jQuery UI

Usually when you get this problem, it happens because a script is trying to reference an element that doesn't exist yet while the page is loading.

As richie mentioned: "The HTML parser will parse the HTML content from top to bottom..."

So you can add your JavaScript references to the bottom of the HTML file. This will not only improve performance; it will also ensure that all elements referenced in your script files have already been loaded by the HTML parser.

So you could have something like this:

<html>
    <head>
        <!--  Style sheet references and CSS definitions -->
    </head>
    <body>
        <!-- HTML markup and other page content -->

        <!-- JavaScript references. You could include jQuery here as well and do all your scripting here. -->
    </body>
</html>

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

submit a form in a new tab

Try using jQuery

<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>

Here is a full answer - http://ftutorials.com/open-html-form-in-new-tab/

Reading string by char till end of line C/C++

You want to use single quotes:

if(c=='\0')

Double quotes (") are for strings, which are sequences of characters. Single quotes (') are for individual characters.

However, the end-of-line is represented by the newline character, which is '\n'.

Note that in both cases, the backslash is not part of the character, but just a way you represent special characters. Using backslashes you can represent various unprintable characters and also characters which would otherwise confuse the compiler.

A monad is just a monoid in the category of endofunctors, what's the problem?

Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.

Below is my original answer.


It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.

What is the memory consumption of an object in Java?

I've gotten very good results from the java.lang.instrument.Instrumentation approach mentioned in another answer. For good examples of its use, see the entry, Instrumentation Memory Counter from the JavaSpecialists' Newsletter and the java.sizeOf library on SourceForge.

Create Table from View

If you want to create a new A you can use INTO;

select * into A from dbo.myView

How to draw a custom UIView that is just a circle - iPhone app

My contribution with a Swift extension:

extension UIView {
    func asCircle() {
        self.layer.cornerRadius = self.frame.width / 2;
        self.layer.masksToBounds = true
    }
}

Just call myView.asCircle()

What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

This project references NuGet package(s) that are missing on this computer

I easily solve this problem by right clicking on my solution and then clicking on the Enable NuGet Package Restore option

(P.S: Ensure that you have the Nuget Install From Tools--> Extensions and Update--> Nuget Package Manager for Visual Studio 2013. If not install this extention first)

Hope it helps.

How to run vi on docker container?

If you actually want a small editor for simple housekeeping in a docker, use this in your Dockerfile:

RUN apt-get install -y busybox && ln -s /bin/busybox /bin/vi

I used it on an Ubuntu 18 based docker. (Of course you might need an RUN apt-get update before it but if you are making your own Docker file you probably already have that.)

Reverse a string in Java

    public static void reverseString(String s){
        System.out.println("---------");
        for(int i=s.length()-1; i>=0;i--){
            System.out.print(s.charAt(i));    
        }
        System.out.println(); 

    }

Select Specific Columns from Spark DataFrame

If you want to split you dataframe into two different ones, do two selects on it with the different columns you want.

 val sourceDf = spark.read.csv(...)
 val df1 = sourceDF.select("first column", "second column", "third column")
 val df2 = sourceDF.select("first column", "second column", "third column")

Note that this of course means that the sourceDf would be evaluated twice, so if it can fit into distributed memory and you use most of the columns across both dataframes it might be a good idea to cache it. It it has many extra columns that you don't need, then you can do a select on it first to select on the columns you will need so it would store all that extra data in memory.

JavaScript pattern for multiple constructors

JavaScript doesn't have function overloading, including for methods or constructors.

If you want a function to behave differently depending on the number and types of parameters you pass to it, you'll have to sniff them manually. JavaScript will happily call a function with more or fewer than the declared number of arguments.

function foo(a, b) {
    if (b===undefined) // parameter was omitted in call
        b= 'some default value';

    if (typeof(a)==='string')
        this._constructInSomeWay(a, b);
    else if (a instanceof MyType)
        this._constructInSomeOtherWay(a, b);
}

You can also access arguments as an array-like to get any further arguments passed in.

If you need more complex arguments, it can be a good idea to put some or all of them inside an object lookup:

function bar(argmap) {
    if ('optionalparam' in argmap)
        this._constructInSomeWay(argmap.param, argmap.optionalparam);
    ...
}

bar({param: 1, optionalparam: 2})

Python demonstrates how default and named arguments can be used to cover the most use cases in a more practical and graceful way than function overloading. JavaScript, not so much.

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

MSDN Documentation Here

To add a bit of context to M.Ali's Answer you can convert a string to a uniqueidentifier using the following code

   SELECT CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E')

If that doesn't work check to make sure you have entered a valid GUID

Using Thymeleaf when the value is null

This can also be handled using the elvis operator ?: which will add a default value when the field is null:

<span th:text="${object.property} ?: 'default value'"></span>

Jquery to get SelectedText from dropdown

If you're using a <select>, $(this).val() inside the change() event returns the value of the current selected option. Using text() is redundant most of the time, since it's usually identical to the value, and in case is different, you'll probably end up using the value in the back-end and not the text. So you can just do this:

http://jsfiddle.net/elclanrs/DW5kF/

var selectedText2 = $(this).val();

EDIT: Note that in case your value attribute is empty, most browsers use the contents as value, so it'll work either way.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

#Write this on anaconda prompt in admin mode
conda install -c anaconda graphviz
conda install -c conda-forge python-graphviz
conda install -c conda-forge/label/broken python-graphviz
conda install -c conda-forge/label/cf201901 python-graphviz
conda install -c conda-forge/label/cf202003 python-graphviz

#check dot -v in window's cmd prompt
C:\WINDOWS\system32>dot -V
dot - graphviz version 2.38.0 (20140413.2041)
(this means graphviz installed successfully)

#Add path to sys and user eve variables
PATH
C:\Anaconda3\pkgs\graphviz-2.38-hfd603c8_2\Library\bin
(search bin folder of graphviz and then copy n paste path in env variables)

#Re-run all cmds in jyupter notebook
#if error occurs (less chances)
#then 
#Restart anaconda and again run all cmds in jyupter notebook
eg.
import graphviz as gp
with open("tree.dot") as f:
    dot_read=f.read()
display(gp.Source(dot_read))

how to get text from textview

You have to do the following:

a=a.replace("\n"," ");
a=a.trim();
String b[]=a.split("+");
int k=Integer.ValueOf(b[0]);
int l=Integer.ValueOf(b[1]);
int sum=k+l;

How to get a user's client IP address in ASP.NET?

use in ashx file

public string getIP(HttpContext c)
{
    string ips = c.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (!string.IsNullOrEmpty(ips))
    {
        return ips.Split(',')[0];
    }
    return c.Request.ServerVariables["REMOTE_ADDR"];
}

No process is on the other end of the pipe (SQL Server 2012)

To solve this, connect to SQL Management Studio using Windows Authentication, then right-click on server node Properties->Security and enable SQL Server and Windows Authentication mode. If you're using 'sa' make sure the account is enabled. To do this open 'sa' under Logins and view Status.

enable sa admin

If this didn't work, you may need to reinstall SQL Server

Database, Table and Column Naming Conventions?

  1. No. A table should be named after the entity it represents. Person, not persons is how you would refer to whoever one of the records represents.
  2. Again, same thing. The column FirstName really should not be called FirstNames. It all depends on what you want to represent with the column.
  3. NO.
  4. Yes. Case it for clarity. If you need to have columns like "FirstName", casing will make it easier to read.

Ok. Thats my $0.02

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Stop embedded youtube iframe?

Talvi's answer may still work, but that Youtube Javascript API has been marked as deprecated. You should now be using the newer Youtube IFrame API.

The documentation provides a few ways to accomplish video embedding, but for your goal, you'd include the following:

//load the IFrame Player API code asynchronously
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//will be youtube player references once API is loaded
var players = [];

//gets called once the player API has loaded
function onYouTubeIframeAPIReady() {
    $('.myiframeclass').each(function() {
        var frame = $(this);

        //create each instance using the individual iframe id
        var player = new YT.Player(frame.attr('id'));

        players.push(player);
    });
}

//global stop button click handler
$('#mybutton').click(function(){

    //loop through each Youtube player instance and call stopVideo()
    for (var i in players) {
        var player = players[i];
        player.stopVideo();
    }
});

How do I get a list of locked users in an Oracle database?

Found it!

SELECT username, 
       account_status
  FROM dba_users;

git rebase merge conflict

If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".

First, checkout temp branch and start standard merge

git checkout -b temp
git merge origin/master

You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.

git commit -m "Merge branch 'origin/master' into 'temp'"

Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.

git checkout alpha
git rebase origin/master -X theirs

Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.

git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)

And delete temporary branch

git branch -D temp

That's all. We did a rebase via hidden merge.

Also I wrote a script, so that can be done in a dialog manner, you can find it here.

Implement touch using Python?

It might seem logical to create a string with the desired variables, and pass it to os.system:

touch = 'touch ' + dir + '/' + fileName
os.system(touch)

This is inadequate in a number of ways (e.g.,it doesn't handle whitespace), so don't do it.

A more robust method is to use subprocess :

subprocess.call(['touch', os.path.join(dirname, fileName)])

While this is much better than using a subshell (with os.system), it is still only suitable for quick-and-dirty scripts; use the accepted answer for cross-platform programs.

Importing JSON into an Eclipse project

on linux pip install library_that_you_need Also on Help/Eclipse MarketPlace, i add PyDev IDE for Eclipse 7, so when i start a new project i create file/New Project/Pydev Project

Does a foreign key automatically create an index?

I notice that Entity Framework 6.1 pointed at MSSQL does automatically add indexes on foreign keys.

Calculate percentage saved between two numbers?

This is function with inverted option

It will return:

  • 'change' - string that you can use for css class in your template
  • 'result' - plain result
  • 'formatted' - formatted result

function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){

    $value      = $newNumber - $oldNumber;

    $change     = '';
    $sign       = '';

    $result     = 0.00;

    if ( $invert ) {
         if ( $value > 0 ) {
        //  going UP
            $change             = 'up';
            $sign               = '+';
            if ( $oldNumber > 0 ) {
                $result         = ($newNumber / $oldNumber) * 100;
            } else {
                $result     = 100.00;
            }

        }elseif ( $value < 0 ) {        
        //  going DOWN
            $change             = 'down';
            //$value                = abs($value);
            $result             = ($oldNumber / $newNumber) * 100;
            $result             = abs($result);
            $sign               = '-';

        }else {
        //  no changes
        }

    }else{

        if ( $newNumber > $oldNumber ) {

            //  increase
            $change             = 'up';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            }else{
                $result = 100.00;
            }

            $sign               = '+';

        }elseif ( $oldNumber > $newNumber ) {

            //  decrease
            $change             = 'down';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            } else {
                $result = 100.00;
            }

            $sign               = '-';

        }else{

            //  no change

        }

        $result = abs($result);

    }

    $result_formatted       = number_format($result, 2);

    if ( $invert ) {
        if ( $change == 'up' ) {
            $change = 'down';
        }elseif ( $change == 'down' ) {
            $change = 'up';
        }else{
            //
        }

        if ( $sign == '+' ) {
            $sign = '-';
        }elseif ( $sign == '-' ) {
            $sign = '+';
        }else{
            //
        }
    }
    if ( $format ) {
        $formatted          = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
    } else{
        $formatted          = $result_formatted;
    }

    return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}

Reversing a string in C

Rather than breaking half-way through, you should simply shorten your loop.

size_t length = strlen(str);
size_t i;

for (i = 0; i < (length / 2); i++)
{
    char temp = str[length - i - 1];
    str[length - i - 1] = str[i];
    str[i] = temp;
}

CSS center display inline block?

This will horizontally center an inline-block element without needing to modify its parent's styles:

  display: inline-block;
  position: relative;
  // Move the element to the left by 50% of the container's width
  left: 50%; 
  // Calculates 50% of the element's width, and moves it by that
  // amount across the X-axis to the left
  transform: translateX(-50%);

What is code coverage and how do YOU measure it?

Code coverage basically tells you how much of your code is covered under tests. For example, if you have 90% code coverage, it means 10% of the code is not covered under tests.

I know you might be thinking that if 90% of the code is covered, it's good enough, but you have to look from a different angle. What is stopping you from getting 100% code coverage?

A good example will be this:

if(customer.IsOldCustomer()) 
{
}
else 
{
}

Now, in the code above, there are two paths/branches. If you are always hitting the "YES" branch, you are not covering the "else" part and it will be shown in the Code Coverage results. This is good because now you know that what is not covered and you can write a test to cover the "else" part. If there was no code coverage, you are just sitting on a time bomb, waiting to explode.

NCover is a good tool to measure code coverage.

Fastest Way of Inserting in Entity Framework

[NEW SOLUTION FOR POSTGRESQL] Hey, I know it's quite an old post, but I have recently run into similar problem, but we were using Postgresql. I wanted to use effective bulkinsert, what turned out to be pretty difficult. I haven't found any proper free library to do so on this DB. I have only found this helper: https://bytefish.de/blog/postgresql_bulk_insert/ which is also on Nuget. I have written a small mapper, which auto mapped properties the way Entity Framework:

public static PostgreSQLCopyHelper<T> CreateHelper<T>(string schemaName, string tableName)
        {
            var helper = new PostgreSQLCopyHelper<T>("dbo", "\"" + tableName + "\"");
            var properties = typeof(T).GetProperties();
            foreach(var prop in properties)
            {
                var type = prop.PropertyType;
                if (Attribute.IsDefined(prop, typeof(KeyAttribute)) || Attribute.IsDefined(prop, typeof(ForeignKeyAttribute)))
                    continue;
                switch (type)
                {
                    case Type intType when intType == typeof(int) || intType == typeof(int?):
                        {
                            helper = helper.MapInteger("\"" + prop.Name + "\"",  x => (int?)typeof(T).GetProperty(prop.Name).GetValue(x, null));
                            break;
                        }
                    case Type stringType when stringType == typeof(string):
                        {
                            helper = helper.MapText("\"" + prop.Name + "\"", x => (string)typeof(T).GetProperty(prop.Name).GetValue(x, null));
                            break;
                        }
                    case Type dateType when dateType == typeof(DateTime) || dateType == typeof(DateTime?):
                        {
                            helper = helper.MapTimeStamp("\"" + prop.Name + "\"", x => (DateTime?)typeof(T).GetProperty(prop.Name).GetValue(x, null));
                            break;
                        }
                    case Type decimalType when decimalType == typeof(decimal) || decimalType == typeof(decimal?):
                        {
                            helper = helper.MapMoney("\"" + prop.Name + "\"", x => (decimal?)typeof(T).GetProperty(prop.Name).GetValue(x, null));
                            break;
                        }
                    case Type doubleType when doubleType == typeof(double) || doubleType == typeof(double?):
                        {
                            helper = helper.MapDouble("\"" + prop.Name + "\"", x => (double?)typeof(T).GetProperty(prop.Name).GetValue(x, null));
                            break;
                        }
                    case Type floatType when floatType == typeof(float) || floatType == typeof(float?):
                        {
                            helper = helper.MapReal("\"" + prop.Name + "\"", x => (float?)typeof(T).GetProperty(prop.Name).GetValue(x, null));
                            break;
                        }
                    case Type guidType when guidType == typeof(Guid):
                        {
                            helper = helper.MapUUID("\"" + prop.Name + "\"", x => (Guid)typeof(T).GetProperty(prop.Name).GetValue(x, null));
                            break;
                        }
                }
            }
            return helper;
        }

I use it the following way (I had entity named Undertaking):

var undertakingHelper = BulkMapper.CreateHelper<Model.Undertaking>("dbo", nameof(Model.Undertaking));
undertakingHelper.SaveAll(transaction.UnderlyingTransaction.Connection as Npgsql.NpgsqlConnection, undertakingsToAdd));

I showed an example with transaction, but it can also be done with normal connection retrieved from context. undertakingsToAdd is enumerable of normal entity records, which I want to bulkInsert into DB.

This solution, to which I've got after few hours of research and trying, is as you could expect much faster and finally easy to use and free! I really advice you to use this solution, not only for the reasons mentioned above, but also because it's the only one with which I had no problems with Postgresql itself, many other solutions work flawlessly for example with SqlServer.

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

How do I parse a URL into hostname and path in javascript?

The AngularJS way - fiddle here: http://jsfiddle.net/PT5BG/4/

<!DOCTYPE html>
<html>
<head>
    <title>Parse URL using AngularJS</title>
</head>
<body ng-app ng-controller="AppCtrl" ng-init="init()">

<h3>Parse URL using AngularJS</h3>

url: <input type="text" ng-model="url" value="" style="width:780px;">

<ul>
    <li>href = {{parser.href}}</li>
    <li>protocol = {{parser.protocol}}</li>
    <li>host = {{parser.host}}</li>
    <li>hostname = {{parser.hostname}}</li>
    <li>port = {{parser.port}}</li>
    <li>pathname = {{parser.pathname}}</li>
    <li>hash = {{parser.hash}}</li>
    <li>search = {{parser.search}}</li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

<script>
function AppCtrl($scope) {

    $scope.$watch('url', function() {
        $scope.parser.href = $scope.url;
    });

    $scope.init = function() {
        $scope.parser = document.createElement('a');
        $scope.url = window.location;
    }

}
</script>

</body>
</html>

Display a tooltip over a button using Windows Forms

Using the form designer:

  • Drag the ToolTip control from the Toolbox, onto the form.
  • Select the properties of the control you want the tool tip to appear on.
  • Find the property 'ToolTip on toolTip1' (the name may not be toolTip1 if you changed it's default name).
  • Set the text of the property to the tool tip text you would like to display.

You can set also the tool tip programatically using the following call:

this.toolTip1.SetToolTip(this.targetControl, "My Tool Tip");

How to write to a JSON file in the correct format

This question is for ruby 1.8 but it still comes on top when googling.

in ruby >= 1.9 you can use

File.write("public/temp.json",tempHash.to_json)

other than what mentioned in other answers, in ruby 1.8 you can also use one liner form

File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

Date format in the json output using spring boot

You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.

You should do two things

  • add spring.jackson.serialization.write-dates-as-timestamps:false in your application.properties this will disable converting dates to timestamps and instead use a ISO-8601 compliant format

  • You can than customize the format by annotating the getter method of you dateOfBirth property with @JsonFormat(pattern="yyyy-MM-dd")

Matplotlib discrete colorbar

The above answers are good, except they don't have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:

import matplotlib.pyplot as plt
import numpy as np

def discrete_matshow(data):
    #get discrete colormap
    cmap = plt.get_cmap('RdBu', np.max(data)-np.min(data)+1)
    # set limits .5 outside true range
    mat = plt.matshow(data,cmap=cmap,vmin = np.min(data)-.5, vmax = np.max(data)+.5)
    #tell the colorbar to tick at integers
    cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))

#generate data
a=np.random.randint(1, 9, size=(10, 10))
discrete_matshow(a)

example of discrete colorbar

Bash foreach loop

cat `cat filenames.txt`

will do the trick

SQLite UPSERT / UPDATE OR INSERT

The problem with all presented answers it complete lack of taking triggers (and probably other side effects) into account. Solution like

INSERT OR IGNORE ...
UPDATE ...

leads to both triggers executed (for insert and then for update) when row does not exist.

Proper solution is

UPDATE OR IGNORE ...
INSERT OR IGNORE ...

in that case only one statement is executed (when row exists or not).

Add new line in text file with Windows batch file

I believe you are using the

echo Text >> Example.txt 

function?

If so the answer would be simply adding a "." (Dot) directly after the echo with nothing else there.

Example:

echo Blah
echo Blah 2
echo. #New line is added
echo Next Blah

Why does Google prepend while(1); to their JSON responses?

It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.

Contrived example: say Google has a URL like mail.google.com/json?action=inbox which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script> tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.

The while(1); or &&&BLAH&&& prevents this: an AJAX request at mail.google.com will have full access to the text content, and can strip it away. But a <script> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.

This does not address the issue of cross-site request forgery.

How to get calendar Quarter from a date in TSQL

Try this one

SELECT  CONCAT (TO_CHAR(sysdate,'YYYY-'),concat ('Q',TO_CHAR(sysdate,'Q') ))from dual

Replace sysdate with your own column name with date type format and dual with your table name

Best way to update an element in a generic List

You could do:

var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));

This will return the matching dog, else it will return null.

You can then set the property like follows:

if (matchingDog != null)
    matchingDog.Name = "New Dog Name";

Remove pattern from string with gsub

The following code works on your example :

gsub(".*_", "", a)

How can I remove text within parentheses with a regex?

If you don't absolutely need to use a regex, useconsider using Perl's Text::Balanced to remove the parenthesis.

use Text::Balanced qw(extract_bracketed);

my ($extracted, $remainder, $prefix) = extract_bracketed( $filename, '()', '[^(]*' );

{   no warnings 'uninitialized';

    $filename = (defined $prefix or defined $remainder)
                ? $prefix . $remainder
                : $extracted;
}

You may be thinking, "Why do all this when a regex does the trick in one line?"

$filename =~ s/\([^}]*\)//;

Text::Balanced handles nested parenthesis. So $filename = 'foo_(bar(baz)buz)).foo' will be extracted properly. The regex based solutions offered here will fail on this string. The one will stop at the first closing paren, and the other will eat them all.

   $filename =~ s/\([^}]*\)//;
   # returns 'foo_buz)).foo'

   $filename =~ s/\(.*\)//;
   # returns 'foo_.foo'

   # text balanced example returns 'foo_).foo'

If either of the regex behaviors is acceptable, use a regex--but document the limitations and the assumptions being made.

ASP.NET MVC 3 Razor - Adding class to EditorFor

As of ASP.NET MVC 5.1, adding a class to an EditorFor is possible (the original question specified ASP.NET MVC 3, and the accepted answer is still the best with that considered).

@Html.EditorFor(x=> x.MyProperty,
    new { htmlAttributes = new { @class = "MyCssClass" } })

See: What's New in ASP.NET MVC 5.1, Bootstrap support for editor templates

Delete/Reset all entries in Core Data?

here my swift3 version for delete all records. 'Users' is entity name

@IBAction func btnDelAll_touchupinside(_ sender: Any) {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObjectContext = appDelegate.persistentContainer.viewContext

    let fetchReq = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    let req = NSBatchDeleteRequest(fetchRequest: fetchReq)

    do {
        try managedObjectContext.execute(req)

    } catch {
        // Error Handling
    }   
}

How do I get list of methods in a Python class?

def find_defining_class(obj, meth_name):
    for ty in type(obj).mro():
        if meth_name in ty.__dict__:
            return ty

So

print find_defining_class(car, 'speedometer') 

Think Python page 210

Performance of FOR vs FOREACH in PHP

One thing to watch out for in benchmarks (especially phpbench.com), is even though the numbers are sound, the tests are not. Alot of the tests on phpbench.com are doing things at are trivial and abuse PHP's ability to cache array lookups to skew benchmarks or in the case of iterating over an array doesn't actually test it in real world cases (no one writes empty for loops). I've done my own benchmarks that I've found are fairly reflective of the real world results and they always show the language's native iterating syntax foreach coming out on top (surprise, surprise).

//make a nicely random array
$aHash1 = range( 0, 999999 );
$aHash2 = range( 0, 999999 );
shuffle( $aHash1 );
shuffle( $aHash2 );
$aHash = array_combine( $aHash1, $aHash2 );


$start1 = microtime(true);
foreach($aHash as $key=>$val) $aHash[$key]++;
$end1 = microtime(true);

$start2 = microtime(true);
while(list($key) = each($aHash)) $aHash[$key]++;
$end2 = microtime(true);


$start3 = microtime(true);
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) $aHash[$key[$i]]++;
$end3 = microtime(true);

$start4 = microtime(true);
foreach($aHash as &$val) $val++;
$end4 = microtime(true);

echo "foreach ".($end1 - $start1)."\n"; //foreach 0.947947025299
echo "while ".($end2 - $start2)."\n"; //while 0.847212076187
echo "for ".($end3 - $start3)."\n"; //for 0.439476966858
echo "foreach ref ".($end4 - $start4)."\n"; //foreach ref 0.0886030197144

//For these tests we MUST do an array lookup,
//since that is normally the *point* of iteration
//i'm also calling noop on it so that PHP doesn't
//optimize out the loopup.
function noop( $value ) {}

//Create an array of increasing indexes, w/ random values
$bHash = range( 0, 999999 );
shuffle( $bHash );

$bstart1 = microtime(true);
for($i = 0; $i < 1000000; ++$i) noop( $bHash[$i] );
$bend1 = microtime(true);

$bstart2 = microtime(true);
$i = 0; while($i < 1000000) { noop( $bHash[$i] ); ++$i; }
$bend2 = microtime(true);


$bstart3 = microtime(true);
foreach( $bHash as $value ) { noop( $value ); }
$bend3 = microtime(true);

echo "for ".($bend1 - $bstart1)."\n"; //for 0.397135972977
echo "while ".($bend2 - $bstart2)."\n"; //while 0.364789962769
echo "foreach ".($bend3 - $bstart3)."\n"; //foreach 0.346374034882

SQL Server datetime LIKE select?

Try this

SELECT top 10 * from record WHERE  IsActive = 1 and CONVERT(VARCHAR, register_date, 120) LIKE '2020-01%'

SQL Server Management Studio, how to get execution time down to milliseconds

Turn on Client Statistics by doing one of the following:

  • Menu: Query > Include client Statistics
  • Toolbar: Click the button (next to Include Actual Execution Time)
  • Keyboard: Shift-Alt-S

Then you get a new tab which records the timings, IO data and rowcounts etc for (up to) the last 10 exections (plus averages!):

enter image description here

Using :: in C++

You're pretty much right about cout and cin. They are objects (not functions) defined inside the std namespace. Here are their declarations as defined by the C++ standard:

Header <iostream> synopsis

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;

  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}

:: is known as the scope resolution operator. The names cout and cin are defined within std, so we have to qualify their names with std::.

Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:

class foo
{
  public:
    foo();
    void bar();
};

The constructor named foo is a member of the class named foo. They have the same name because its the constructor. The function bar is also a member of foo.

Because they are members of foo, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar outside the class, you need to do it like so:

foo::foo()
{
  // Implement the constructor
}

void foo::bar()
{
  // Implement bar
}

This is because they are being defined outside the class. If you had not put the foo:: qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo. For example, this is entirely different bar:

void bar()
{
  // Implement different bar
}

It's allowed to have the same name as the function in the foo class because it's in a different scope. This bar is in the global scope, whereas the other bar belonged to the foo class.

Maintain/Save/Restore scroll position when returning to a ListView

If you're using fragments hosted on an activity you can do something like this:

public abstract class BaseFragment extends Fragment {
     private boolean mSaveView = false;
     private SoftReference<View> mViewReference;

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          if (mSaveView) {
               if (mViewReference != null) {
                    final View savedView = mViewReference.get();
                    if (savedView != null) {
                         if (savedView.getParent() != null) {
                              ((ViewGroup) savedView.getParent()).removeView(savedView);
                              return savedView;
                         }
                    }
               }
          }

          final View view = inflater.inflate(getFragmentResource(), container, false);
          mViewReference = new SoftReference<View>(view);
          return view;
     }

     protected void setSaveView(boolean value) {
           mSaveView = value;
     }
}

public class MyFragment extends BaseFragment {
     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          setSaveView(true);
          final View view = super.onCreateView(inflater, container, savedInstanceState);
          ListView placesList = (ListView) view.findViewById(R.id.places_list);
          if (placesList.getAdapter() == null) {
               placesList.setAdapter(createAdapter());
          }
     }
}

What's the difference between `raw_input()` and `input()` in Python 3?

In Python 3, raw_input() doesn't exist which was already mentioned by Sven.

In Python 2, the input() function evaluates your input.

Example:

name = input("what is your name ?")
what is your name ?harsha

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    name = input("what is your name ?")
  File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined

In the example above, Python 2.x is trying to evaluate harsha as a variable rather than a string. To avoid that, we can use double quotes around our input like "harsha":

>>> name = input("what is your name?")
what is your name?"harsha"
>>> print(name)
harsha

raw_input()

The raw_input()` function doesn't evaluate, it will just read whatever you enter.

Example:

name = raw_input("what is your name ?")
what is your name ?harsha
>>> name
'harsha'

Example:

 name = eval(raw_input("what is your name?"))
what is your name?harsha

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    name = eval(raw_input("what is your name?"))
  File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined

In example above, I was just trying to evaluate the user input with the eval function.

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].

  1. Go to 'Object Explorer' of SQL Management Studio.
  2. Expand Security, then Login.
  3. Select the user you are working with, then right click and select Properties Windows.
  4. In Select a Page, Go to Server Roles
  5. Click on sysadmin and save.

Design Android EditText to show error message as described by google

reVerse's answer is great but it didn't point out how to remove the floating error tooltip kind of thing

You'll need edittext.setError(null) to remove that.
Also, as someone pointed out, you don't need TextInputLayout.setErrorEnabled(true)

Layout

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter something" />
</android.support.design.widget.TextInputLayout>

Code

TextInputLayout til = (TextInputLayout) editText.getParent();
til.setError("Your input is not valid...");
editText.setError(null);

How to update a plot in matplotlib?

This worked for me. Repeatedly calls a function updating the graph every time.

import matplotlib.pyplot as plt
import matplotlib.animation as anim

def plot_cont(fun, xmax):
    y = []
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)

    def update(i):
        yi = fun()
        y.append(yi)
        x = range(len(y))
        ax.clear()
        ax.plot(x, y)
        print i, ': ', yi

    a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
    plt.show()

"fun" is a function that returns an integer. FuncAnimation will repeatedly call "update", it will do that "xmax" times.

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

System.currentTimeMillis() is obviously the most efficient since it does not even create an object, but new Date() is really just a thin wrapper about a long, so it is not far behind. Calendar, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and all the oddities that are inherent to dates and times (leap years, daylight savings, timezones, etc.).

It's generally a good idea to deal only with long timestamps or Date objects within your application, and only use Calendar when you actually need to perform date/time calculations, or to format dates for displaying them to the user. If you have to do a lot of this, using Joda Time is probably a good idea, for the cleaner interface and better performance.

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Finding the next available id in MySQL

I don't think you can ever be sure on the next id, because someone might insert a new row just after you asked for the next id. You would at least need a transaction, and if I'm not mistaken you can only get the actual id used after inserting it, at least that is the common way of handling it -- see http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

How to use this boolean in an if statement?

The problem here is

if (stop = true) is an assignation not a comparision.

Try if (stop == true)

Also take a look to the Top Ten Errors Java Programmers Make.

How to compile LEX/YACC files on Windows?

You can find the latest windows version of flex & bison here: http://sourceforge.net/projects/winflexbison/

Can HTML checkboxes be set to readonly?

@(Model.IsEnabled) Use this condition for dynamically check and uncheck and set readonly if check box is already checked.

 <input id="abc" name="abc"  type="checkbox" @(Model.IsEnabled ? "checked=checked onclick=this.checked=!this.checked;" : string.Empty) >

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

class calc{
public static void main(String args[])
{
    int a, b, c;
    char ch;
    do{

        Scanner s=new Scanner(System.in);

                System.out.print("1. Addition\n");
                System.out.print("2. Substraction\n");
                System.out.print("3. Multiplication\n");
                System.out.print("4. Division\n");
                System.out.print("5. Exit\n\n");

                System.out.print("Enter your choice : ");
                ch=s.next().charAt(0);
                    switch (ch)
                    {
                        case '1' :
                        Addition chose1=new Addition();
                        chose1.add();
                        break;

                        case '2' :
                        Substraction chose2=new Substraction();
                        chose2.sub();
                        break;

                        case '3' :
                        Multiplication chose3= new Multiplication();
                        chose3.multi();
                        break;

                        case '4' :
                        Division chose4=new Division();
                        chose4.divi();
                        break;

                        case '5' :
                        System.exit(0);
                        break;

                        default :
                        System.out.print("wrong choice!!!");
                        break;
                    }
        System.out.print("\n--------------------------\n");                     
    }while(ch !=5); 
}

}

In the above code when its System.exit(0); and when i press case 5 it exits properly but when i use System.exit(1); and press case 5 it exits with error and again when i try with case 15 it exits properly by this i got to know that, when ever we put any int inside argument it specifies that, it take the character from that position i.e if i put (4) that it means take 5th character from that string if its (3) then it means take 4th character from that inputed string

Hive load CSV with commas in quoted fields

If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:

ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';

Will accept this line as 4 fields

1,some text\, with comma in it,123,more text

How to add white spaces in HTML paragraph

This can be done easily and cleanly with float.

Demo: jsfiddle.net/KcdpW

HTML:

<ul>
    <li>Item 1 <span class="right">(1)</span></li>
    <li>Item 2 <span class="right">(2)</span></li>
</ul>?

CSS:

ul {
    width: 10em
}
.right {
    float: right
}?

How to set locale in DatePipe in Angular 2?

I've had a look in date_pipe.ts and it has two bits of info which are of interest. near the top are the following two lines:

// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';

Near the bottom is this line:

return DateFormatter.format(value, defaultLocale, pattern);

This suggests to me that the date pipe is currently hard-coded to be 'en-US'.

Please enlighten me if I am wrong.

Meaning of Open hashing and Closed hashing

The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).

For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.

The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.

Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".

In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".

Django DoesNotExist

Nice way to handle not found error in Django.

https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#get-object-or-404

from django.shortcuts import get_object_or_404

def get_data(request):
    obj = get_object_or_404(Model, pk=1)

default select option as blank

This should help :

https://www.w3schools.com/tags/att_select_required.asp

_x000D_
_x000D_
 <form>_x000D_
 <select required>_x000D_
  <option value="">None</option>_x000D_
  <option value="volvo">Volvo</option>_x000D_
  <option value="saab">Saab</option>_x000D_
  <option value="mercedes">Mercedes</option>_x000D_
  <option value="audi">Audi</option>_x000D_
</select>_x000D_
<button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Write values in app.config file

As others mentioned, you can do this with ConfigurationManager.AppSettings.Settings. But: Using Settings[key] = value will not work if the key doesn't exist.
Using Settings.Add(key, value), if the key already exists, it will join the new value to its value(s) separated by a comma, something like <add key="myKey" value="value1, value2, value3" />

To avoid these unexpected results, you have to handle two scenario's

  • If entry with the given key exists? then update its value
  • if entry with the given key doesn't exist? then create new entry(key,value)

Code

public static void Set(string key, string value)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    var entry = config.AppSettings.Settings[key];
    if (entry == null)
        config.AppSettings.Settings.Add(key, value);
    else
        config.AppSettings.Settings[key].Value = value;

    config.Save(ConfigurationSaveMode.Modified);
}

For more info about the check entry == null, check this post.
Hope this will help someone.

How to close Browser Tab After Submitting a Form?

That's because the event onsubmit is triggered before the form is submitted.

Remove your onSubmit and output that JavaScript in your PHP script after you have processed the request. You are closing the window right now, and cancelling the request to your server.

Select all elements with a "data-xxx" attribute without using jQuery

document.querySelectorAll("[data-foo]")

will get you all elements with that attribute.

document.querySelectorAll("[data-foo='1']")

will only get you ones with a value of 1.

Run ScrollTop with offset of element by ID

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;   
if (!isNaN(top)) {
$("#app_scroler").click(function () {   
$('html, body').animate({
            scrollTop: top
        }, 100);
    });
}

if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;

Trees in Twitter Bootstrap

For those still searching for a tree with CSS3, this is a fantastic piece of code I found on the net:

http://thecodeplayer.com/walkthrough/css3-family-tree

HTML

<div class="tree">
  <ul>
    <li>
      <a href="#">Parent</a>
      <ul>
        <li>
          <a href="#">Child</a>
          <ul>
            <li>
              <a href="#">Grand Child</a>
            </li>
          </ul>
        </li>
        <li>
          <a href="#">Child</a>
          <ul>
            <li><a href="#">Grand Child</a></li>
            <li>
              <a href="#">Grand Child</a>
              <ul>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
                <li>
                  <a href="#">Great Grand Child</a>
                </li>
              </ul>
            </li>
            <li><a href="#">Grand Child</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

CSS

* {margin: 0; padding: 0;}

.tree ul {
  padding-top: 20px; position: relative;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

.tree li {
  float: left; text-align: center;
  list-style-type: none;
  position: relative;
  padding: 20px 5px 0 5px;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*We will use ::before and ::after to draw the connectors*/

.tree li::before, .tree li::after{
  content: '';
  position: absolute; top: 0; right: 50%;
  border-top: 1px solid #ccc;
  width: 50%; height: 20px;
}
.tree li::after{
  right: auto; left: 50%;
  border-left: 1px solid #ccc;
}

/*We need to remove left-right connectors from elements without 
any siblings*/
.tree li:only-child::after, .tree li:only-child::before {
  display: none;
}

/*Remove space from the top of single children*/
.tree li:only-child{ padding-top: 0;}

/*Remove left connector from first child and 
right connector from last child*/
.tree li:first-child::before, .tree li:last-child::after{
  border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/
.tree li:last-child::before{
  border-right: 1px solid #ccc;
  border-radius: 0 5px 0 0;
  -webkit-border-radius: 0 5px 0 0;
  -moz-border-radius: 0 5px 0 0;
}
.tree li:first-child::after{
  border-radius: 5px 0 0 0;
  -webkit-border-radius: 5px 0 0 0;
  -moz-border-radius: 5px 0 0 0;
}

/*Time to add downward connectors from parents*/
.tree ul ul::before{
  content: '';
  position: absolute; top: 0; left: 50%;
  border-left: 1px solid #ccc;
  width: 0; height: 20px;
}

.tree li a{
  border: 1px solid #ccc;
  padding: 5px 10px;
  text-decoration: none;
  color: #666;
  font-family: arial, verdana, tahoma;
  font-size: 11px;
  display: inline-block;

  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;

  transition: all 0.5s;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/
.tree li a:hover, .tree li a:hover+ul li a {
  background: #c8e4f8; color: #000; border: 1px solid #94a0b4;
}
/*Connector styles on hover*/
.tree li a:hover+ul li::after, 
.tree li a:hover+ul li::before, 
.tree li a:hover+ul::before, 
.tree li a:hover+ul ul::before{
  border-color:  #94a0b4;
}

PS: apart from the code, I also like the way the site shows it in action... really innovative.

Jenkins - passing variables between jobs?

1.Post-Build Actions > Select ”Trigger parameterized build on other projects”

2.Enter the environment variable with value.Value can also be Jenkins Build Parameters.

Detailed steps can be seen here :-

https://itisatechiesworld.wordpress.com/jenkins-related-articles/jenkins-configuration/jenkins-passing-a-parameter-from-one-job-to-another/

Hope it's helpful :)

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

Just my two cents for future visitors who have this problem.

This is the correct syntax for PHP 5.3, for example if you call static method from the class name:

MyClassName::getConfig($key);

If you previously assign the ClassName to the $cnf variable, you can call the static method from it (we are talking about PHP 5.3):

$cnf = MyClassName;
$cnf::getConfig($key);

However, this sintax doesn't work on PHP 5.2 or lower, and you need to use the following:

$cnf = MyClassName;
call_user_func(array($cnf, "getConfig", $key, ...otherposibleadditionalparameters... ));

Hope this helps people having this error in 5.2 version (don't know if this was openfrog's version).

Android set bitmap to Imageview

There is a library named Picasso which can efficiently load images from a URL. It can also load an image from a file.

Examples:

  1. Load URL into ImageView without generating a bitmap:

    Picasso.with(context) // Context
           .load("http://abc.imgur.com/gxsg.png") // URL or file
           .into(imageView); // An ImageView object to show the loaded image
    
  2. Load URL into ImageView by generating a bitmap:

    Picasso.with(this)
           .load(artistImageUrl)
           .into(new Target() {
               @Override
               public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                   /* Save the bitmap or do something with it here */
    
                   // Set it in the ImageView
                   theView.setImageBitmap(bitmap)
               }
    
               @Override
               public void onBitmapFailed(Drawable errorDrawable) {
    
               }
    
               @Override
               public void onPrepareLoad(Drawable placeHolderDrawable) {
    
               }
           });
    

There are many more options available in Picasso. Here is the documentation.

Angular 2 execute script after template render

ngAfterViewInit() of AppComponent is a lifecycle callback Angular calls after the root component and it's children have been rendered and it should fit for your purpose.

See also https://angular.io/guide/lifecycle-hooks

android - How to get view from context?

Why don't you just use a singleton?

import android.content.Context;


public class ClassicSingleton {
    private Context c=null;
    private static ClassicSingleton instance = null;
    protected ClassicSingleton()
    {
       // Exists only to defeat instantiation.
    }
    public void setContext(Context ctx)
    {
    c=ctx;
    }
    public Context getContext()
    {
       return c;
    }
    public static ClassicSingleton getInstance()
    {
        if(instance == null) {
            instance = new ClassicSingleton();
        }
        return instance;
    }
}

Then in the activity class:

 private ClassicSingleton cs = ClassicSingleton.getInstance();

And in the non activity class:

ClassicSingleton cs= ClassicSingleton.getInstance();
        Context c=cs.getContext();
        ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);

How to convert binary string value to decimal

public static Long binToDec(String bin) {
long dec = 0L;
    long pow = 1L;
    for (int i = (bin.length() - 1); i >= 0; i--) {
        char c = bin.charAt(i);
        dec = dec + (Long.parseLong(c + "") * pow);
        pow = pow * 2;
    }
    return dec;
}

or

long num = Long.parseLong("101110111",2);

How can I output leading zeros in Ruby?

Use String#next as the counter.

>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003

next is relatively 'clever', meaning you can even go for

>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003

Disallow Twitter Bootstrap modal window from closing

I believe you want to set the backdrop value to static. If you want to avoid the window to close when using the Esc key, you have to set another value.

Example:

<a data-controls-modal="your_div_id"
   data-backdrop="static"
   data-keyboard="false"
   href="#">

OR if you are using JavaScript:

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
});

Using an attribute of the current class instance as a default value for method's parameter

Default value for parameters are evaluated at "compilation", once. So obviously you can't access self. The classic example is list as default parameter. If you add elements into it, the default value for the parameter changes!

The workaround is to use another default parameter, typically None, and then check and update the variable.

jquery how to use multiple ajax calls one after the end of the other

I consider the following to be more pragmatic since it does not sequence the ajax calls but that is surely a matter of taste.

function check_ajax_call_count()
{
    if ( window.ajax_call_count==window.ajax_calls_completed )
    {
        // do whatever needs to be done after the last ajax call finished
    }
}
window.ajax_call_count = 0;
window.ajax_calls_completed = 10;
setInterval(check_ajax_call_count,100);

Now you can iterate window.ajax_call_count inside the success part of your ajax requests until it reaches the specified number of calls send (window.ajax_calls_completed).

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

in SQL*Plus you could also use a REFCURSOR variable:

SQL> VARIABLE x REFCURSOR
SQL> DECLARE
  2   V_Sqlstatement Varchar2(2000);
  3  BEGIN
  4   V_Sqlstatement := 'SELECT * FROM DUAL';
  5   OPEN :x for v_Sqlstatement;
  6  End;
  7  /

ProcÚdure PL/SQL terminÚe avec succÞs.

SQL> print x;

D
-
X

Apache default VirtualHost

The NameVirtualHost option would be a good option.

How to delete session cookie in Postman?

Is the Postman Interceptor enabled? Toggling it will route all requests and responses through the Chrome browser.

Interceptor - https://www.getpostman.com/docs/capture Cookies documentation - http://blog.getpostman.com/index.php/2014/11/28/using-the-interceptor-to-read-and-write-cookies/

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

Try the following commands

~$ sudo /etc/init.d/mysql stop
~$ sudo mysqld_safe --skip-grant-tables &
~$ mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

mysql> use mysql;

mysql> update user set password=PASSWORD("root") where User='root';

mysql> flush privileges;

mysql> quit

~$ sudo /etc/init.d/mysql stop

Stopping MySQL database server: mysqld

STOPPING server from pid file /var/run/mysqld/mysqld.pid

mysqld_safe[6186]: ended

[1]+  Done                    mysqld_safe --skip-grant-tables

~$ sudo /etc/init.d/mysql start

~$ mysql -u root -p

* MySQL Community Server 5.6.35 is started
~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.35 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Expand a random range from 1–5 to 1–7

By using a rolling total, you can both

  • maintain an equal distribution; and
  • not have to sacrifice any element in the random sequence.

Both these problems are an issue with the simplistic rand(5)+rand(5)...-type solutions. The following Python code shows how to implement it (most of this is proving the distribution).

import random
x = []
for i in range (0,7):
    x.append (0)
t = 0
tt = 0
for i in range (0,700000):
    ########################################
    #####            qq.py             #####
    r = int (random.random () * 5)
    t = (t + r) % 7
    ########################################
    #####       qq_notsogood.py        #####
    #r = 20
    #while r > 6:
        #r =     int (random.random () * 5)
        #r = r + int (random.random () * 5)
    #t = r
    ########################################
    x[t] = x[t] + 1
    tt = tt + 1
high = x[0]
low = x[0]
for i in range (0,7):
    print "%d: %7d %.5f" % (i, x[i], 100.0 * x[i] / tt)
    if x[i] < low:
        low = x[i]
    if x[i] > high:
        high = x[i]
diff = high - low
print "Variation = %d (%.5f%%)" % (diff, 100.0 * diff / tt)

And this output shows the results:

pax$ python qq.py
0:   99908 14.27257
1:  100029 14.28986
2:  100327 14.33243
3:  100395 14.34214
4:   99104 14.15771
5:   99829 14.26129
6:  100408 14.34400
Variation = 1304 (0.18629%)

pax$ python qq.py
0:   99547 14.22100
1:  100229 14.31843
2:  100078 14.29686
3:   99451 14.20729
4:  100284 14.32629
5:  100038 14.29114
6:  100373 14.33900
Variation = 922 (0.13171%)

pax$ python qq.py
0:  100481 14.35443
1:   99188 14.16971
2:  100284 14.32629
3:  100222 14.31743
4:   99960 14.28000
5:   99426 14.20371
6:  100439 14.34843
Variation = 1293 (0.18471%)

A simplistic rand(5)+rand(5), ignoring those cases where this returns more than 6 has a typical variation of 18%, 100 times that of the method shown above:

pax$ python qq_notsogood.py
0:   31756 4.53657
1:   63304 9.04343
2:   95507 13.64386
3:  127825 18.26071
4:  158851 22.69300
5:  127567 18.22386
6:   95190 13.59857
Variation = 127095 (18.15643%)

pax$ python qq_notsogood.py
0:   31792 4.54171
1:   63637 9.09100
2:   95641 13.66300
3:  127627 18.23243
4:  158751 22.67871
5:  126782 18.11171
6:   95770 13.68143
Variation = 126959 (18.13700%)

pax$ python qq_notsogood.py
0:   31955 4.56500
1:   63485 9.06929
2:   94849 13.54986
3:  127737 18.24814
4:  159687 22.81243
5:  127391 18.19871
6:   94896 13.55657
Variation = 127732 (18.24743%)

And, on the advice of Nixuz, I've cleaned the script up so you can just extract and use the rand7... stuff:

import random

# rand5() returns 0 through 4 inclusive.

def rand5():
    return int (random.random () * 5)

# rand7() generator returns 0 through 6 inclusive (using rand5()).

def rand7():
    rand7ret = 0
    while True:
        rand7ret = (rand7ret + rand5()) % 7
        yield rand7ret

# Number of test runs.

count = 700000

# Work out distribution.

distrib = [0,0,0,0,0,0,0]
rgen =rand7()
for i in range (0,count):
    r = rgen.next()
    distrib[r] = distrib[r] + 1

# Print distributions and calculate variation.

high = distrib[0]
low = distrib[0]
for i in range (0,7):
    print "%d: %7d %.5f" % (i, distrib[i], 100.0 * distrib[i] / count)
    if distrib[i] < low:
        low = distrib[i]
    if distrib[i] > high:
        high = distrib[i]
diff = high - low
print "Variation = %d (%.5f%%)" % (diff, 100.0 * diff / count)

Meaning of delta or epsilon argument of assertEquals for double values

I just want to mention the great AssertJ library. It's my go to assertion library for JUnit 4 and 5 and also solves this problem elegantly:

assertThat(actual).isCloseTo(expectedDouble, within(delta))

adding .css file to ejs

You can use this

     var fs = require('fs');
     var myCss = {
         style : fs.readFileSync('./style.css','utf8');
     };

     app.get('/', function(req, res){
       res.render('index.ejs', {
       title: 'My Site',
       myCss: myCss
      });
     });

put this on template

   <%- myCss.style %>

just build style.css

  <style>
    body { 
     background-color: #D8D8D8;
     color: #444;
   }
  </style>

I try this for some custom css. It works for me