Programs & Examples On #Castle dynamicproxy

Castle DynamicProxy is a library for generating lightweight .NET proxies on the fly at runtime. Proxy objects allow calls to members of an object to be intercepted without modifying the code of the class.

Storing a file in a database as opposed to the file system?

The overhead of having to parse a blob (image) into a byte array and then write it to disk in the proper file name and then reading it is enough of an overhead hit to discourage you from doing this too often, especially if the files are rather large.

ClassNotFoundException com.mysql.jdbc.Driver

Ok..May be i can also contribute my solution.. Right click on project -properties -->Deployment assembly...there you need to add the mysql-connector-java.jar and apply it...which makes your prject configured with web-Libraries that has this sql connector...This worked for me.. I hope this works for you guys as well

Configuring so that pip install can work from github

you can try this way in Colab

!git clone https://github.com/UKPLab/sentence-transformers.git
!pip install -e /content/sentence-transformers
import sentence_transformers

Git - Ignore files during merge

Here git-update-index - Register file contents in the working tree to the index.

git update-index --assume-unchanged <PATH_OF_THE_FILE>

Example:-

git update-index --assume-unchanged somelocation/pom.xml

Using group by on multiple columns

In simple English from GROUP BY with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.

Look at the following example for reference. Here I'm using International football results from 1872 to 2020

+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|       _c0|             _c1|     _c2|_c3|_c4|     _c5|      _c6|                _c7|  _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30|        Scotland| England|  0|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1873-03-08|         England|Scotland|  4|  2|Friendly|   London|            England|FALSE|
|1874-03-07|        Scotland| England|  2|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1875-03-06|         England|Scotland|  2|  2|Friendly|   London|            England|FALSE|
|1876-03-04|        Scotland| England|  3|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1876-03-25|        Scotland|   Wales|  4|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1877-03-03|         England|Scotland|  1|  3|Friendly|   London|            England|FALSE|
|1877-03-05|           Wales|Scotland|  0|  2|Friendly|  Wrexham|              Wales|FALSE|
|1878-03-02|        Scotland| England|  7|  2|Friendly|  Glasgow|           Scotland|FALSE|
|1878-03-23|        Scotland|   Wales|  9|  0|Friendly|  Glasgow|           Scotland|FALSE|
|1879-01-18|         England|   Wales|  2|  1|Friendly|   London|            England|FALSE|
|1879-04-05|         England|Scotland|  5|  4|Friendly|   London|            England|FALSE|
|1879-04-07|           Wales|Scotland|  0|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-13|        Scotland| England|  5|  4|Friendly|  Glasgow|           Scotland|FALSE|
|1880-03-15|           Wales| England|  2|  3|Friendly|  Wrexham|              Wales|FALSE|
|1880-03-27|        Scotland|   Wales|  5|  1|Friendly|  Glasgow|           Scotland|FALSE|
|1881-02-26|         England|   Wales|  0|  1|Friendly|Blackburn|            England|FALSE|
|1881-03-12|         England|Scotland|  1|  6|Friendly|   London|            England|FALSE|
|1881-03-14|           Wales|Scotland|  1|  5|Friendly|  Wrexham|              Wales|FALSE|
|1882-02-18|Northern Ireland| England|  0| 13|Friendly|  Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+

And now I'm going to group by similar country(column _c7) and tournament(_c5) value pairs by GROUP BY operation,

SELECT `_c5`,`_c7`,count(*)  FROM res GROUP BY `_c5`,`_c7`

+--------------------+-------------------+--------+
|                 _c5|                _c7|count(1)|
+--------------------+-------------------+--------+
|            Friendly|  Southern Rhodesia|      11|
|            Friendly|            Ecuador|      68|
|African Cup of Na...|           Ethiopia|      41|
|Gold Cup qualific...|Trinidad and Tobago|       9|
|AFC Asian Cup qua...|             Bhutan|       7|
|African Nations C...|              Gabon|       2|
|            Friendly|           China PR|     170|
|FIFA World Cup qu...|             Israel|      59|
|FIFA World Cup qu...|              Japan|      61|
|UEFA Euro qualifi...|            Romania|      62|
|AFC Asian Cup qua...|              Macau|       9|
|            Friendly|        South Sudan|       1|
|CONCACAF Nations ...|           Suriname|       3|
|         Copa Newton|          Argentina|      12|
|            Friendly|        Philippines|      38|
|FIFA World Cup qu...|              Chile|      68|
|African Cup of Na...|         Madagascar|      29|
|FIFA World Cup qu...|       Burkina Faso|      30|
| UEFA Nations League|            Denmark|       4|
|        Atlantic Cup|           Paraguay|       2|
+--------------------+-------------------+--------+

Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.

Note: Here it's mandatory to use a counter column in this case.

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

Statement stmt3 = con.createStatement();

ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");

count = rs3.getInt("count");

Define global constants

In Angular 4, you can use environment class to keep all your globals.

You have environment.ts and environment.prod.ts by default.

For example

export const environment = {
  production: false,
  apiUrl: 'http://localhost:8000/api/'
};

And then on your service:

import { environment } from '../../environments/environment';
...
environment.apiUrl;

MySQL IF ELSEIF in select query

For your question :

SELECT id, 
   IF(qty_1 <= '23', price,
   IF(('23' > qty_1 && qty_2 <= '23'), price_2,
   IF(('23' > qty_2 && qty_3 <= '23'), price_3,
   IF(('23' > qty_2 && qty_3<='23'), price_3,
   IF('23' > qty_3, price_4, 1))))) as total 
FROM product;

You can use the if - else control structure or the IF function in MySQL.

Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

horizontal line and right way to code it in html, css

_x000D_
_x000D_
hr {_x000D_
    display: block;_x000D_
    height: 1px;_x000D_
    border: 0;_x000D_
    border-top: 1px solid #ccc;_x000D_
    margin: 1em 0;_x000D_
    padding: 0;_x000D_
}
_x000D_
<div>Hello</div>_x000D_
<hr/>_x000D_
<div>World</div>
_x000D_
_x000D_
_x000D_

Here is how html5boilerplate does it:

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

Turning Sonar off for certain code

Use //NOSONAR on the line you get warning if it is something you cannot help your code with. It works!

What does git push -u mean?

This is no longer up-to-date!

Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.

Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.

How to find a text inside SQL Server procedures / triggers?

[Late answer but hopefully usefull]

Using system tables doesn't always give 100% correct results because there might be a possibility that some stored procedures and/or views are encrypted in which case you'll need to use DAC connection to get the data you need.

I'd recommend using a third party tool such as ApexSQL Search that can deal with encrypted objects easily.

Syscomments system table will give null value for text column in case object is encrypted.

batch script - read line by line

For those with spaces in the path, you are going to want something like this: n.b. It expands out to an absolute path, rather than relative, so if your running directory path has spaces in, these count too.

set SOURCE=path\with spaces\to\my.log
FOR /F "usebackq delims=" %%A IN ("%SOURCE%") DO (
    ECHO %%A
)

To explain:

(path\with spaces\to\my.log)

Will not parse, because spaces. If it becomes:

("path\with spaces\to\my.log")

It will be handled as a string rather than a file path.

"usebackq delims=" 

See docs will allow the path to be used as a path (thanks to Stephan).

Android: Difference between Parcelable and Serializable?

Implementation of parcelable can be faster if you use paracelable plugin in android studio. search for Android Parcelable code generator

MongoDB or CouchDB - fit for production?

We are running CouchDB as a replacemant for MySQL for our shops (70.0000 items/shop, a total of 4 million attributes of all items, cross connections between items).

Our goals were:

  1. Easy replication from a master-db to several clients with different documents.

  2. Fast pre-calculated data like "how many parts do I have with this attribute and that filter, fitting to those conditions"

facts:

  1. Our shops are now running much faster than with MySQL (and mysql-database needed additionaly 1-3 days of pre-calculating (so updating was twice a month), making the data ready for product counting and filtering, CouchDB needs 5 hours, so we could update product data every night)
  2. Setting up (filtered) data distribution & backups to the shop nodes is fast and easy

but also:

  1. Understanding map/reduce and the limits of not having joins is quite hard
  2. No operation on data like "delete where" or "update where" without external programs
  3. Replication works well, unless there is a problem; then it's really hard to find out what was the reason (for beginners)
  4. The installation of CouchDB without binaries (yes there are a some in the wild, but not for every OS/version) could be hard, if you are not a Linux geek. But the CouchDB Community is helpful (#couchdb), and luckily there are companies out there (cloudant, iriscouch) that offer services from free to big business.
  5. CouchDB is moving forward, so there are a lot of changes (improvements) going on that might change they way you work. But basic things remain stable.

As a result: MySQL as a database for data creation and maintaining is reliable and easy to understand and handle. I think we will not change this. But I also don't want to miss the power of CouchDB views and the ease of replication setup.

Production couches sometimes caused trouble after months of work due to misconfiguration and forgotten logrotates (view building takes too long or hangs, replication stops), but never lost data, and always could be easily reset.

UIScrollView scroll to bottom programmatically

I also found another useful way of doing this in the case you are using a UITableview (which is a subclass of UIScrollView):

[(UITableView *)self.view scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

How can I convert a .py to .exe for Python?

I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

Here's the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?

How to rotate x-axis tick labels in Pandas barplot

The question is clear but the title is not as precise as it could be. My answer is for those who came looking to change the axis label, as opposed to the tick labels, which is what the accepted answer is about. (The title has now been corrected).

for ax in plt.gcf().axes:
    plt.sca(ax)
    plt.xlabel(ax.get_xlabel(), rotation=90)

How to determine MIME type of file in android?

The above solution returned null in case of .rar file, using URLConnection.guessContentTypeFromName(url) worked in this case.

SELECTING with multiple WHERE conditions on same column

can't really see your table, but flag cannot be both 'Volunteer' and 'Uploaded'. If you have multiple values in a column, you can use

WHERE flag LIKE "%Volunteer%" AND flag LIKE "%UPLOADED%"

not really applicable seeing the formatted table.

'printf' vs. 'cout' in C++

With primitives, it probably doesn't matter entirely which one you use. I say where it gets usefulness is when you want to output complex objects.

For example, if you have a class,

#include <iostream>
#include <cstdlib>

using namespace std;

class Something
{
public:
        Something(int x, int y, int z) : a(x), b(y), c(z) { }
        int a;
        int b;
        int c;

        friend ostream& operator<<(ostream&, const Something&);
};

ostream& operator<<(ostream& o, const Something& s)
{
        o << s.a << ", " << s.b << ", " << s.c;
        return o;
}

int main(void)
{
        Something s(3, 2, 1);

        // output with printf
        printf("%i, %i, %i\n", s.a, s.b, s.c);

        // output with cout
        cout << s << endl;

        return 0;
}

Now the above might not seem all that great, but let's suppose you have to output this in multiple places in your code. Not only that, let's say you add a field "int d." With cout, you only have to change it in once place. However, with printf, you'd have to change it in possibly a lot of places and not only that, you have to remind yourself which ones to output.

With that said, with cout, you can reduce a lot of times spent with maintenance of your code and not only that if you re-use the object "Something" in a new application, you don't really have to worry about output.

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

What does <![CDATA[]]> in XML mean?

The Cdata is a data which you may want to pass to an xml parser and still not interpreted as an xml.

Say for eg :- You have an xml which has encapsulates question/answer object . Such open fields can have any data which does not strictly fall under basic data type or xml defined custom data types. Like --Is this a correct tag for xml comment ? .-- You may have a requirement to pass it as it is without being interpreted by the xml parser as another child element. Here Cdata comes to your rescue . By declaring as Cdata you are telling the parser don't treat the data wrapped as an xml (though it may look like one )

PHP GuzzleHttp. How to make a post request with params?

$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
    'body' => json_encode($dataArray)
]);
$response = $request->getBody();

Add

openssl.cafile in php.ini file

Are PHP short tags acceptable to use?

No, and they're being phased out by PHP 6 so if you appreciate code longevity, simply don't use them or the <% ... %> tags.

How to retrieve the dimensions of a view?

You should rather look at View lifecycle: http://developer.android.com/reference/android/view/View.html Generally you should not know width and height for sure until your activity comes to onResume state.

How to check if a service is running via batch file and start it, if it is not running?

I just found this thread and wanted to add to the discussion if the person doesn't want to use a batch file to restart services. In Windows there is an option if you go to Services, service properties, then recovery. Here you can set parameters for the service. Like to restart the service if the service stops. Also, you can even have a second fail attempt do something different as in restart the computer.

Intent from Fragment to Activity

Hope this code will help

public class ThisFragment extends Fragment {

public Button button = null;
Intent intent;

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

    View rootView = inflater.inflate(R.layout.yourlayout, container, false);

    intent = new Intent(getActivity(), GoToThisActivity.class);
    button = (Button) rootView.findViewById(R.id.theButtonid);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(intent);
        }
    });
    return rootView;
}

You can use this code, make sure you change "ThisFragment" as your fragment name, "yourlayout" as the layout name, "GoToThisActivity" change it to which activity do you want and then "theButtonid" change it with your button id you used.

How to use ConcurrentLinkedQueue?

This is largely a duplicate of another question.

Here's the section of that answer that is relevant to this question:

Do I need to do my own synchronization if I use java.util.ConcurrentLinkedQueue?

Atomic operations on the concurrent collections are synchronized for you. In other words, each individual call to the queue is guaranteed thread-safe without any action on your part. What is not guaranteed thread-safe are any operations you perform on the collection that are non-atomic.

For example, this is threadsafe without any action on your part:

queue.add(obj);

or

queue.poll(obj);

However; non-atomic calls to the queue are not automatically thread-safe. For example, the following operations are not automatically threadsafe:

if(!queue.isEmpty()) {
   queue.poll(obj);
}

That last one is not threadsafe, as it is very possible that between the time isEmpty is called and the time poll is called, other threads will have added or removed items from the queue. The threadsafe way to perform this is like this:

synchronized(queue) {
    if(!queue.isEmpty()) {
       queue.poll(obj);
    }
}

Again...atomic calls to the queue are automatically thread-safe. Non-atomic calls are not.

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

If you get an exception for : Invalid column type

Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()

 List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
 getRowMapper());

Note that the second two arguments are swapped around.

How to make a char string from a C macro's value?

#include <stdio.h>

#define QUOTEME(x) #x

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME QUOTEME(TEST_FUN)
#endif

int main(void)
{
    puts(TEST_FUN_NAME);
    return 0;
}

Reference: Wikipedia's C preprocessor page

How to read the output from git diff?

On my mac:

info diff then select: Output formats -> Context -> Unified format -> Detailed Unified :

Or online man diff on gnu following the same path to the same section:

File: diff.info, Node: Detailed Unified, Next: Example Unified, Up: Unified Format

Detailed Description of Unified Format ......................................

The unified output format starts with a two-line header, which looks like this:

 --- FROM-FILE FROM-FILE-MODIFICATION-TIME
 +++ TO-FILE TO-FILE-MODIFICATION-TIME

The time stamp looks like `2002-02-21 23:30:39.942229878 -0800' to indicate the date, time with fractional seconds, and time zone.

You can change the header's content with the `--label=LABEL' option; see *Note Alternate Names::.

Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks look like this:

 @@ FROM-FILE-RANGE TO-FILE-RANGE @@
  LINE-FROM-EITHER-FILE
  LINE-FROM-EITHER-FILE...

The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left print column:

`+' A line was added here to the first file.

`-' A line was removed here from the first file.

Maven: How to include jars, which are not available in reps into a J2EE project?

Create a repository folder under your project. Let's take

${project.basedir}/src/main/resources/repo

Then, install your custom jar to this repo:

mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \ 
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]

Lastly, add the following repo and dependency definitions to the projects pom.xml:

<repositories>
    <repository>
        <id>project-repo</id>
        <url>file://${project.basedir}/src/main/resources/repo</url>
    </repository>
</repositories>

<dependencies>    
    <dependency>
        <groupId>[GROUP]</groupId>
        <artifactId>[ARTIFACT]</artifactId>
        <version>[VERS]</version>
    </dependency>
</dependencies>

How to recover closed output window in netbeans?

Easy way, just write some wrong code and Run > Build it will show the error in output window.

I tried all of the above but no success, just this one worked.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

How to get WordPress post featured image URL

You will try this

<?php $url = wp_get_attachment_url(get_post_thumbnail_id($post->ID), 'full'); ?> // Here you can manage your image size like medium, thumbnail, or custom size
    <img src="<?php echo $url ?>" 
/>

Docker official registry (Docker Hub) URL

It's just docker pull busybox, are you using an up to date version of the docker client. I think they stopped supporting clients lower than 1.5.

Incidentally that curl works for me:

$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]

Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.

Run a single migration file

If you've implemented a change method like this:

class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
  end
end

You can create an instance of the migration and run migrate(:up) or migrate(:down) on an instance, like this:

$ rails console
>> require "db/migrate/20090408054532_add_part_number_to_products.rb"
>> AddPartNumberToProducts.new.migrate(:down)

What is the difference between pull and clone in git?

While the git fetch command will fetch down all the changes on the server that you don’t have yet, it will not modify your working directory at all. It will simply get the data for you and let you merge it yourself. However, there is a command called git pull which is essentially a git fetch immediately followed by a git merge in most cases.

Read more: https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches#Pulling

makefile:4: *** missing separator. Stop

make has a very stupid relationship with tabs. All actions of every rule are identified by tabs. And, no, four spaces don't make a tab. Only a tab makes a tab.

To check, I use the command cat -e -t -v makefile_name.

It shows the presence of tabs with ^I and line endings with $. Both are vital to ensure that dependencies end properly and tabs mark the action for the rules so that they are easily identifiable to the make utility.

Example:

Kaizen ~/so_test $ cat -e -t -v  mk.t
all:ll$      ## here the $ is end of line ...                   
$
ll:ll.c   $
^Igcc  -c  -Wall -Werror -02 c.c ll.c  -o  ll  $@  $<$ 
## the ^I above means a tab was there before the action part, so this line is ok .
 $
clean :$
   \rm -fr ll$
## see here there is no ^I which means , tab is not present .... 
## in this case you need to open the file again and edit/ensure a tab 
## starts the action part

Is calculating an MD5 hash less CPU intensive than SHA family functions?

As someone who's spent a bit of time optimizing MD5 performance, I thought I'd supply more of a technical explanation than the benchmarks provided here, to anyone who happens to find this in the future.

MD5 does less "work" than SHA1 (e.g. fewer compression rounds), so one may think it should be faster. However, the MD5 algorithm is mostly one big dependency chain, which means that it doesn't exploit modern superscalar processors particularly well (i.e. exhibits low instructions-per-clock). SHA1 has more parallelism available, so despite needing more "computational work" done, it often ends up being faster than MD5 on modern superscalar processors.
If you do the MD5 vs SHA1 comparison on older processors or ones with less superscalar "width" (such as a Silvermont based Atom CPU), you'll generally find MD5 is faster than SHA1.

SHA2 and SHA3 are even more compute intensive than SHA1, and generally much slower.
One thing to note, however, is that some new x86 and ARM CPUs have instructions to accelerate SHA1 and SHA256, which obviously helps these algorithms greatly if the instructions are being used.

As an aside, SHA256 and SHA512 performance may exhibit similarly curious behaviour. SHA512 does more "work" than SHA256, however a key difference between the two is that SHA256 operates using 32-bit words, whilst SHA512 operates using 64-bit words. As such, SHA512 will generally be faster than SHA256 on a platform with a 64-bit word size, as it's processing twice the amount of data at once. Conversely, SHA256 should outperform SHA512 on a platform with a 32-bit word size.

Note that all of the above only applies to single buffer hashing (by far the most common use case). If you're fancy and computing multiple hashes in parallel, i.e. a multi-buffer SIMD approach, the behaviour changes somewhat.

Why can't I declare static methods in an interface?

It seems the static method in the interface might be supported in Java 8, well, my solution is just define them in the inner class.

interface Foo {
    // ...
    class fn {
        public static void func1(...) {
            // ...
        }
    }
}

The same technique can also be used in annotations:

public @interface Foo {
    String value();

    class fn {
        public static String getValue(Object obj) {
            Foo foo = obj.getClass().getAnnotation(Foo.class);
            return foo == null ? null : foo.value();
        }
    }
}

The inner class should always be accessed in the form of Interface.fn... instead of Class.fn..., then, you can get rid of ambiguous problem.

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

Adb over wireless without usb cable at all for not rooted phones

For your question

Adb over wireless without USB cable at all for not rooted phones

 You can't do it for now without USB cable.

But you have an option:

Note: You need put USB at least once to achieve the following:

You need to connect your device to your computer via USB cable. Make sure USB debugging is working. You can check if it shows up when running adb devices.

Open cmd in ...\AppData\Local\Android\sdk\platform-tools

Step1: Run adb devices

Ex: C:\pathToSDK\platform-tools>adb devices

You can check if it shows up when running adb devices.

Step2: Run adb tcpip 5555

Ex: C:\pathToSDK\platform-tools>adb tcpip 5555

Disconnect your device (remove the USB cable).

Step3: Go to the Settings -> About phone -> Status to view the IP address of your phone.

.

Step4: Run `adb connect

Ex: C:\pathToSDK\platform-tools>adb connect 192.168.0.2

Step5: Run adb devices again, you should see your device.

Now you can execute adb commands or use your favourite IDE for android development - wireless!

Now you might ask, what do I have to do when I move into a different work space and change WiFi networks? You do not have to repeat steps 1 to 3 (these set your phone into WiFi-debug mode). You do have to connect to your phone again by executing steps 4 to 6.

Unfortunately, the android phones lose the WiFi-debug mode when restarting. Thus, if your battery died, you have to start over. Otherwise, if you keep an eye on your battery and do not restart your phone, you can live without a cable for weeks!

See here for more

Happy wireless coding!

Ref: https://futurestud.io/tutorials/how-to-debug-your-android-app-over-wifi-without-root

UPDATE:

If you set C:\pathToSDK\platform-tools this path in Environment variables then there is no need to repeat all steps, you can simply use only Step 4 that's it, it will connect to your device.

To set path : My Computer-> Right click--> properties -> Advanced system settings -> Environment variables -> edit path in System variables -> paste the platform-tools path in variable value -> ok -> ok -> ok

EntityType has no key defined error

i know that this post is late but this solution helped me:

    [Key]
    [Column(Order = 0)]
    public int RoleId { get; set; }

added [Column(Order = 0)] after [Key] can be added by increment by 1:

    [Key]
    [Column(Order = 1)]
    public int RoleIdName { get; set; }

etc...

JQuery datepicker language

Include js files of datepicker and language (locales)

'resource/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
'resource/bower_components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.sv.min.js',

In the options of the datepicker, set the language as below:

$('.datepicker').datepicker({'language' : 'sv'});

Attach (open) mdf file database with SQL Server Management Studio

I had the same problem.

system configuration:-single system with window 7 sp1 server and client both are installed on same system

I was trying to access the window desktop. As some the answer say that your Sqlserver service don't have full access to the directory. This is totally right.

I solved this problem by doing a few simple steps

  1. Go to All Programs->microsoft sql server 2008 -> configuration tools and then select sql server configuration manager.
  2. Select the service and go to properties. In the build in Account dialog box select local system and then select ok button.

enter image description here

Steps 3 and 4 in image are demo with accessing the folder

creating json object with variables

var formValues = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    phone: $('#phoneNumber').val(),
    address: $('#address').val()
};

Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

How should I read a file line-by-line in Python?

There is exactly one reason why the following is preferred:

with open('filename.txt') as fp:
    for line in fp:
        print line

We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file "quickly enough" without the with block if they use some other scheme to reclaim memory.

In such an implementation, you might get a "too many files open" error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by every function that could encounter the error, including those in libraries. What a nightmare.

Or you could just use the with block.

Bonus Question

(Stop reading now if are only interested in the objective aspects of the question.)

Why isn't that included in the iterator protocol for file objects?

This is a subjective question about API design, so I have a subjective answer in two parts.

On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines and close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.

Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called "lazy IO" which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the with block in Python.

On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:

with open('filename.txt') as fp:
    for line in fp:
        ...
    fp.seek(0)
    for line in fp:
        ...

While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.

Composability is one of the most important usability features of a language or API.

Set default option in mat-select

On your typescript file, just assign this domain on modeSelect on Your ngOnInit() method like below:



 ngOnInit() {
        this.modeSelect = "domain";
      }

And on your html, use your select list.

<mat-form-field>
        <mat-select  [(value)]="modeSelect" placeholder="Mode">
          <mat-option value="domain">Domain</mat-option>
          <mat-option value="exact">Exact</mat-option>
        </mat-select>
      </mat-form-field>

Move entire line up and down in Vim

Move a line up: ddkP

Move a line down: ddp

Settings to Windows Firewall to allow Docker for Windows to share drive

Even after ensuring that the inbound firewall rule is set up properly and even after uninstalling and reinstalling the File and Printing Sharing Service it didn't work for me.

Solution: on top of that I also had to do a third thing. I had to deactivate the checkbox Prevent incoming connections when on a public network in the specific firewall settings for public networks. After doing that it started working for me as well. See screenshots attached at the end of this message.

Don't know how long this option has been there already. I'm currently working on Win 10 Pro 1709 16299.402.


1. Open specific firewall settings for public networks Open specific firewall settings for public networks

2. Uncheck this checkbox Uncheck this checkbox

SimpleDateFormat parsing date with 'Z' literal

With regards to JSR-310 another project of interest might be threetenbp.

JSR-310 provides a new date and time library for Java SE 8. This project is the backport to Java SE 6 and 7.

In case you are working on an Android project you might want to checkout the ThreeTenABP library.

compile "com.jakewharton.threetenabp:threetenabp:${version}"

JSR-310 was included in Java 8 as the java.time.* package. It is a full replacement for the ailing Date and Calendar APIs in both Java and Android. JSR-310 was backported to Java 6 by its creator, Stephen Colebourne, from which this library is adapted.

How do I compare two strings in python?

Something like this:

if string1 == string2:
    print 'they are the same'

update: if you want to see if each sub-string may exist in the other:

elem1 = [x for x in string1.split()]
elem2 = [x for x in string2.split()]

for item in elem1:
    if item in elem2:
        print item

Scala Doubles, and Precision

How about :

 val value = 1.4142135623730951

//3 decimal places
println((value * 1000).round / 1000.toDouble)

//4 decimal places
println((value * 10000).round / 10000.toDouble)

How to view the contents of an Android APK file?

You can also see the contents of an APK file within the Android device itself, which helps a lot in debugging.

All files including the manifest of an app can be viewed and also shared using email, cloud etc., no rooting required. App is available from:

https://play.google.com/store/apps/details?id=com.dasmic.android.apkpeek

Disclaimer: I am the author of this app.

Java: String - add character n-times

In case of Java 8 you can do:

int n = 4;
String existing = "...";
String result = existing + String.join("", Collections.nCopies(n, "*"));

Output:

...****

In Java 8 the String.join method was added. But Collections.nCopies is even in Java 5.

WSDL/SOAP Test With soapui

  • yes, first ensure you added "?wsdl" to your "http......whatever.svc" link.
    • That didn't fix my problem, though. I had to create a new WCF project from the beginning and manually copy the code. That fixed it. Good luck.

And most important!!!

When you change a namespace in your code, also make sure you change it in web.config!

Displaying better error message than "No JSON object could be decoded"

You wont be able to get python to tell you where the JSON is incorrect. You will need to use a linter online somewhere like this

This will show you error in the JSON you are trying to decode.

Change a column type from Date to DateTime during ROR migration

There's a change_column method, just execute it in your migration with datetime as a new type.

change_column(:my_table, :my_column, :my_new_type)

Python "\n" tag extra line

The print function in python adds itself \n

You could use

import sys
sys.stdout.write(a)

instead

jQuery has deprecated synchronous XMLHTTPRequest

It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:

When you update the content of an element with new html using jQuery/javascript, and this new html contains <script> tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.

You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR in the console window. (firefox).

Android Open External Storage directory(sdcard) for storing file

I had been having the exact same problem!

To get the internal SD card you can use

String extStore = System.getenv("EXTERNAL_STORAGE");
File f_exts = new File(extStore);

To get the external SD card you can use

String secStore = System.getenv("SECONDARY_STORAGE");
File f_secs = new File(secStore);

On running the code

 extStore = "/storage/emulated/legacy"
 secStore = "/storage/extSdCarcd"

works perfectly!

Rendering React Components from Array of Objects

There are couple of way which can be used.

const stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)

Solution 1

<p>{callList.join(', ')}</p>

Solution 2

<ol>    
  { callList && callList.map(item => <li>{item}</li>) }
</ol>

Edit kind-antonelli-z8372

Of course there are other ways also available.

Create a new object from type parameter in generic class

This is what I do to retain type info:

class Helper {
   public static createRaw<T>(TCreator: { new (): T; }, data: any): T
   {
     return Object.assign(new TCreator(), data);
   }
   public static create<T>(TCreator: { new (): T; }, data: T): T
   {
      return this.createRaw(TCreator, data);
   }
}

...

it('create helper', () => {
    class A {
        public data: string;
    }
    class B {
        public data: string;
        public getData(): string {
            return this.data;
        }
    }
    var str = "foobar";

    var a1 = Helper.create<A>(A, {data: str});
    expect(a1 instanceof A).toBeTruthy();
    expect(a1.data).toBe(str);

    var a2 = Helper.create(A, {data: str});
    expect(a2 instanceof A).toBeTruthy();
    expect(a2.data).toBe(str);

    var b1 = Helper.createRaw(B, {data: str});
    expect(b1 instanceof B).toBeTruthy();
    expect(b1.data).toBe(str);
    expect(b1.getData()).toBe(str);

});

Prevent Caching in ASP.NET MVC for specific actions using an attribute

You can use the built in cache attribute to prevent caching.

For .net Framework: [OutputCache(NoStore = true, Duration = 0)]

For .net Core: [ResponseCache(NoStore = true, Duration = 0)]

Be aware that it is impossible to force the browser to disable caching. The best you can do is provide suggestions that most browsers will honor, usually in the form of headers or meta tags. This decorator attribute will disable server caching and also add this header: Cache-Control: public, no-store, max-age=0. It does not add meta tags. If desired, those can be added manually in the view.

Additionally, JQuery and other client frameworks will attempt to trick the browser into not using it's cached version of a resource by adding stuff to the url, like a timestamp or GUID. This is effective in making the browser ask for the resource again but doesn't really prevent caching.

On a final note. You should be aware that resources can also be cached in between the server and client. ISP's, proxies, and other network devices also cache resources and they often use internal rules without looking at the actual resource. There isn't much you can do about these. The good news is that they typically cache for shorter time frames, like seconds or minutes.

PHP append one array to another (not array_push or +)

array_merge is the elegant way:

$a = array('a', 'b');
$b = array('c', 'd');
$merge = array_merge($a, $b); 
// $merge is now equals to array('a','b','c','d');

Doing something like:

$merge = $a + $b;
// $merge now equals array('a','b')

Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b, it won't do anything.

How can I find the current OS in Python?

https://docs.python.org/library/os.html

To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.

Spring boot - configure EntityManager

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

}

PersistenceConfig

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    @Autowired
    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.url"));
         dataSource.setUsername(env.getProperty("jdbc.username"));
         dataSource.setPassword(env.getProperty("jdbc.password"));
         return dataSource;
     }

     @Bean
     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
         return transactionManager;
     }

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         vendorAdapter.setShowSql(true);
         return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
         entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
         entityManagerFactoryBean.setDataSource(dataSource());
         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
         entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);             
         entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

         return entityManagerFactoryBean;
     }

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();

         properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       
     }

}

Main

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

MyService

@Service
public class MyServiceImpl implements MyService {

    @Inject
    private MyDao myDao;

    @Override
    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList = myDao.select(fromDate, toDate);
    }
}

MyDaoImpl

@Repository
@Transactional
public class MyDaoImpl implements MyDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;
    }

}

Assuming maven project: Properties file should be in src/main/resources/database folder

jdbc.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.

public interface ServiceMarker {

}

Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {

}

a.b.c.entities.Student

//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters

}

a.b.c.converters

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        }
        return Timestamp.valueOf(dateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        }    
        return timestamp.toLocalDateTime();
    }
}

pom.xml

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.1.RELEASE</org.springframework-version>
    <hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <mysql-connector-java.version>5.1.36</mysql-connector-java.version>
     <junit.version>4.12</junit.version> 
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate-entitymanager.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons-dbcp2.version}</version>
    </dependency>
</dependencies>

<build>
     <finalName>${project.artifactId}</finalName>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
     </plugins>
</build>

Hope it helps. Thanks

How do I copy a string to the clipboard?

You can use winclip32 module! install:

pip install winclip32

to copy:

import winclip32
winclip32.set_clipboard_data(winclip32.UNICODE_STD_TEXT, "some text")

to get:

import winclip32
print(winclip32.get_clipboard_data(winclip32.UNICODE_STD_TEXT))

for more informations: https://pypi.org/project/winclip32/

Display JSON Data in HTML Table

HTML:
 <div id="container"></div>   
JS:


$('#search').click(function() {
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        dataType:"json", //to parse string into JSON object,
        success: function(data){ 

                var len = data.length;
                var txt = "";
                if(len > 0){
                    for(var i=0;i<len;i++){

                            txt = "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
                            $("#container").append(txt);
                    }



        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;
});

Python BeautifulSoup extract text between element

Use .children instead:

from bs4 import NavigableString, Comment
print ''.join(unicode(child) for child in hit.children 
    if isinstance(child, NavigableString) and not isinstance(child, Comment))

Yes, this is a bit of a dance.

Output:

>>> for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
...     print ''.join(unicode(child) for child in hit.children 
...         if isinstance(child, NavigableString) and not isinstance(child, Comment))
... 




      THIS IS MY TEXT

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

Easy way to pull latest of all git submodules

All you need to do now is a simple git checkout

Just make sure to enable it via this global config: git config --global submodule.recurse true

Convert a string into an int

NSString *string = /* Assume this exists. */;
int value = [string intValue];

Flexbox Not Centering Vertically in IE

I found that ie browser have problem to vertically align inner containers, when only the min-height style is set or when height style is missing at all. What I did was to add height style with some value and that fix the issue for me.

for example :

.outer
    {
       display: -ms-flexbox;
       display: -webkit-flex;
       display: flex;

       /* Center vertically */
       align-items: center;

       /*Center horizontaly */
       justify-content: center;

       /*Center horizontaly ie */
       -ms-flex-pack: center;

        min-height: 220px; 
        height:100px;
    }

So now we have height style, but the min-height will overwrite it. That way ie is happy and we still can use min-height.

Hope this is helpful for someone.

How to preview git-pull without doing fetch?

You can fetch from a remote repo, see the differences and then pull or merge.

This is an example for a remote repo called origin and a branch called master tracking the remote branch origin/master:

git checkout master                                                  
git fetch                                        
git diff origin/master
git pull --rebase origin master

Clearing an HTML file upload field via JavaScript

This jQuery worked for me in IE11, Chrome 53, and Firefox 49:

cloned = $("#fileInput").clone(true);
cloned.val("");
$("#fileInput").replaceWith(cloned);

How to call Stored Procedure in Entity Framework 6 (Code-First)?

Nothing have to do... when you are creating dbcontext for code first approach initialize namespace below the fluent API area make list of sp and use it another place where you want.

public partial class JobScheduleSmsEntities : DbContext
{
    public JobScheduleSmsEntities()
        : base("name=JobScheduleSmsEntities")
    {
        Database.SetInitializer<JobScheduleSmsEntities>(new CreateDatabaseIfNotExists<JobScheduleSmsEntities>());
    }

    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<ReachargeDetail> ReachargeDetails { get; set; }
    public virtual DbSet<RoleMaster> RoleMasters { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.Types().Configure(t => t.MapToStoredProcedures());

        //modelBuilder.Entity<RoleMaster>()
        //     .HasMany(e => e.Customers)
        //     .WithRequired(e => e.RoleMaster)
        //     .HasForeignKey(e => e.RoleID)
        //     .WillCascadeOnDelete(false);
    }
    public virtual List<Sp_CustomerDetails02> Sp_CustomerDetails()
    {
        //return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Sp_CustomerDetails02>("Sp_CustomerDetails");
        //  this.Database.SqlQuery<Sp_CustomerDetails02>("Sp_CustomerDetails");
        using (JobScheduleSmsEntities db = new JobScheduleSmsEntities())
        {
           return db.Database.SqlQuery<Sp_CustomerDetails02>("Sp_CustomerDetails").ToList();

        }

    }

}

}

public partial class Sp_CustomerDetails02
{
    public long? ID { get; set; }
    public string Name { get; set; }
    public string CustomerID { get; set; }
    public long? CustID { get; set; }
    public long? Customer_ID { get; set; }
    public decimal? Amount { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public int? CountDay { get; set; }
    public int? EndDateCountDay { get; set; }
    public DateTime? RenewDate { get; set; }
    public bool? IsSMS { get; set; }
    public bool? IsActive { get; set; }
    public string Contact { get; set; }
}

How can I draw vertical text with CSS cross-browser?

The CSS Writing Modes module introduces orthogonal flows with vertical text.

Just use the writing-mode property with the desired value.

_x000D_
_x000D_
span { margin: 20px; }_x000D_
#vertical-lr { writing-mode: vertical-lr; }_x000D_
#vertical-rl { writing-mode: vertical-rl; }_x000D_
#sideways-lr { writing-mode: sideways-lr; }_x000D_
#sideways-rl { writing-mode: sideways-rl; }
_x000D_
<span id="vertical-lr">_x000D_
  ? (1) vertical-lr ?<br />_x000D_
  ? (2) vertical-lr ?<br />_x000D_
  ? (3) vertical-lr ?_x000D_
</span>_x000D_
<span id="vertical-rl">_x000D_
  ? (1) vertical-rl ?<br />_x000D_
  ? (2) vertical-rl ?<br />_x000D_
  ? (3) vertical-rl ?_x000D_
</span>_x000D_
<span id="sideways-lr">_x000D_
  ? (1) sideways-lr ?<br />_x000D_
  ? (2) sideways-lr ?<br />_x000D_
  ? (3) sideways-lr ?_x000D_
</span>_x000D_
<span id="sideways-rl">_x000D_
  ? (1) sideways-rl ?<br />_x000D_
  ? (2) sideways-rl ?<br />_x000D_
  ? (3) sideways-rl ?_x000D_
</span>
_x000D_
_x000D_
_x000D_

TypeError: 'list' object cannot be interpreted as an integer

In playSound(), instead of

for i in range(myList):

try

for i in myList:

This will iterate over the contents of myList, which I believe is what you want. range(myList) doesn't make any sense.

How to get the index of an element in an IEnumerable?

A few years later, but this uses Linq, returns -1 if not found, doesn't create extra objects, and should short-circuit when found [as opposed to iterating over the entire IEnumerable]:

public static int IndexOf<T>(this IEnumerable<T> list, T item)
{
    return list.Select((x, index) => EqualityComparer<T>.Default.Equals(item, x)
                                     ? index
                                     : -1)
               .FirstOr(x => x != -1, -1);
}

Where 'FirstOr' is:

public static T FirstOr<T>(this IEnumerable<T> source, T alternate)
{
    return source.DefaultIfEmpty(alternate)
                 .First();
}

public static T FirstOr<T>(this IEnumerable<T> source, Func<T, bool> predicate, T alternate)
{
    return source.Where(predicate)
                 .FirstOr(alternate);
}

How to get filename without extension from file path in Ruby

Try File.basename

Returns the last component of the filename given in file_name, which must be formed using forward slashes (``/’’) regardless of the separator used on the local file system. If suffix is given and present at the end of file_name, it is removed.

File.basename("/home/gumby/work/ruby.rb")          #=> "ruby.rb"
File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"

In your case:

File.basename("C:\\projects\\blah.dll", ".dll")  #=> "blah"

Where can I download english dictionary database in a text format?

I dont know if its too late, but i thought it would help someone else.

I wanted the same badly...found it eventually.

Maybe its not perfect,but to me its adequate(for my little dictionary app).

http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip

Its not a dump file, but a MYSQL .sql script file

The words are in WN_SYNSET table and the glossary/meaning in the WN_GLOSS table

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Display A Popup Only Once Per User

Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.

$scope.storage = $localStorage; //connects an object to $localstorage

$scope.storage.hasSeenPopup = "false";  // they haven't seen it


$scope.showPopup = function() {  // popup to tell people to turn sound on

    $scope.data = {}
    // An elaborate, custom popup
    var myPopup = $ionicPopup.show({
        template: '<p class="popuptext">Turn Sound On!</p>',
        cssClass: 'popup'

    });        
    $timeout(function() {
        myPopup.close(); //close the popup after 3 seconds for some reason
    }, 2000);
    $scope.storage.hasSeenPopup = "true"; // they've now seen it

};

$scope.playStream = function(show) {
    PlayerService.play(show);

    $scope.audioObject = audioObject; // this allow for styling the play/pause icons

    if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
        $scope.showPopup();
    }
}

Select unique or distinct values from a list in UNIX shell script

You might want to look at the uniq and sort applications.

./yourscript.ksh | sort | uniq

(FYI, yes, the sort is necessary in this command line, uniq only strips duplicate lines that are immediately after each other)

EDIT:

Contrary to what has been posted by Aaron Digulla in relation to uniq's commandline options:

Given the following input:

class
jar
jar
jar
bin
bin
java

uniq will output all lines exactly once:

class
jar
bin
java

uniq -d will output all lines that appear more than once, and it will print them once:

jar
bin

uniq -u will output all lines that appear exactly once, and it will print them once:

class
java

Checking if a collection is empty in Java: which is the best method?

A good example of where this matters in practice is the ConcurrentSkipListSet implementation in the JDK, which states:

Beware that, unlike in most collections, the size method is not a constant-time operation.

This is a clear case where isEmpty() is much more efficient than checking whether size()==0.

You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.

How To Run PHP From Windows Command Line in WAMPServer

The problem you are describing sounds like your version of PHP might be missing the readline PHP module, causing the interactive shell to not work. I base this on this PHP bug submission.

Try running

php -m

And see if "readline" appears in the output.

There might be good reasons for omitting readline from the distribution. PHP is typically executed by a web server; so it is not really need for most use cases. I am sure you can execute PHP code in a file from the command prompt, using:

php file.php

There is also the phpsh project which provides a (better) interactive shell for PHP. However, some people have had trouble running it under Windows (I did not try this myself).

Edit: According to the documentation here, readline is not supported under Windows:

Note: This extension is not available on Windows platforms.

So, if that is correct, your options are:

  • Avoid the interactive shell, and just execute PHP code in files from the command line - this should work well
  • Try getting phpsh to work under Windows

Javascript decoding html entities

Using jQuery the easiest will be:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';

var output = $("<div />").html(text).text();
console.log(output);

DEMO: http://jsfiddle.net/LKGZx/

Ping site and return result in PHP

Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).

Example usage:

require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}

How to find the nearest parent of a Git branch?

You can also try:

git log --graph --decorate

How to sort with lambda in Python

lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)

It will print as following:

[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]

How to add new column to MYSQL table?

for WORDPRESS:

global $wpdb;


$your_table  = $wpdb->prefix. 'My_Table_Name';
$your_column =                'My_Column_Name'; 

if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){  $result= $wpdb->query(
    "ALTER     TABLE $your_table     ADD $your_column     VARCHAR(100)     CHARACTER SET utf8     NOT NULL     "  //you can add positioning phraze: "AFTER My_another_column"
);}

Python: IndexError: list index out of range

Here is your code. I'm assuming you're using python 3 based on the your use of print() and input():

import random

def main():
    #random.seed() --> don't need random.seed()

    #Prompts the user to enter the number of tickets they wish to play.

    #python 3 version:
    tickets = int(input("How many lottery tickets do you want?\n"))

    #Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
    winning_numbers = []
    winnings = 0

    #Generates the winning lotto numbers.
    for i in range(tickets * 5):
        #del winning_numbers[:] what is this line for?
        randNum = random.randint(1,30)
        while randNum in winning_numbers:    
            randNum = random.randint(1,30)
        winning_numbers.append(randNum)

    print(winning_numbers)
    guess = getguess(tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    winningRanks = [0, 0, 10, 500, 20000, 1000000]

    winnings = sum(winningRanks[:nummatches + 1])

    print("You won a total of",winnings,"with",tickets,"tickets.\n")


#Gets the guess from the user.
def getguess(tickets):
    guess = []
    for i in range(tickets):
        bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
        guess.extend(bubble)
        print(bubble)
    return guess

#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
    match = 0
    for i in range(5):
        if guess[i] == winning_numbers[i]:
            match += 1
    return match

main()

Android Debug Bridge (adb) device - no permissions

Stephan's answer works (using sudo adb kill-server), but it is temporary. It must be re-issued after every reboot.

For a permanent solution, the udev config must be modified:

Witrant's answer is the right idea (copied from the official Android documentation). But it's just a template. If that doesn't work for your device, you need to fill in the correct device ID for your device(s).

lsusb

Bus 001 Device 002: ID 05c6:9025 Qualcomm, Inc.
Bus 002 Device 002: ID 0e0f:0003 VMware, Inc. Virtual Mouse
...

Find your android device in the list.

Then use the first half of the ID (4 digits) for the idVendor (the last half is the idProduct, but it is not necessary to get adb working).

sudo vi /etc/udev/rules.d/51-android.rules and add one rule for each unique idVendor:

SUBSYSTEM=="usb", ATTR{idVendor}=="05c6", MODE="0666", GROUP="plugdev"

It's that simple. You don't need all those other fields given in some of the answers. Save the file.

Then reboot. The change is permanent. (Roger shows a way to restart udev, if you don't want to reboot).

npm throws error without sudo

This is the solution I utilized and worked. I tried utilizing whoami never worked.

sudo chown -R $USER /usr/local/lib/node_modules

then

sudo chown -R $USER /usr/local/bin/npm

then

sudo chown -R $USER /usr/local/bin/node

Wait for page load in Selenium

I use node + selenium-webdriver(which version is 3.5.0 now). what I do for this is:

var webdriver = require('selenium-webdriver'),
    driver = new webdriver.Builder().forBrowser('chrome').build();
;
driver.wait(driver.executeScript("return document.readyState").then(state => {
  return state === 'complete';
}))

How do I get an empty array of any size in python?

You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).

But, try this:

a = [0 for x in range(N)]  # N = size of list you want
a[i] = 5  # as long as i < N, you're okay

For lists of other types, use something besides 0. None is often a good choice as well.

SQL SERVER, SELECT statement with auto generate row id

Do you want an incrementing integer column returned with your recordset? If so: -

--Check for existance  
if  exists (select * from dbo.sysobjects where [id] = object_id(N'dbo.t') AND objectproperty(id, N'IsUserTable') = 1)  
drop table dbo.t
go

--create dummy table and insert data  
create table dbo.t(x char(1) not null primary key, y char(1) not null)  
go  
set nocount on  
insert dbo.t (x,y) values ('A','B')  
insert dbo.t (x,y) values ('C','D')  
insert dbo.t (x,y) values ('E','F')

--create temp table to add an identity column  
create table dbo.#TempWithIdentity(i int not null identity(1,1) primary key,x char(1) not null unique,y char(1) not null)  

--populate the temporary table  
insert into dbo.#TempWithIdentity(x,y) select x,y from dbo.t

--return the data  
select i,x,y from dbo.#TempWithIdentity

--clean up  
drop table dbo.#TempWithIdentity

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

You can do this in the 'Conditional Formatting' tool in the Home tab of Excel 2010.

Assuming the existing rule is 'Use a formula to dtermine which cells to format':

Edit the existing rule, so that the 'Formula' refers to relative rows and columns (i.e. remove $s), and then in the 'Applies to' box, click the icon to make the sheet current and select the cells you want the formatting to apply to (absolute cell references are ok here), then go back to the tool panel and click Apply.

This will work assuming the relative offsets are appropriate throughout your desired apply-to range.

You can copy conditional formatting from one cell to another or a range using copy and paste-special with formatting only, assuming you do not mind copying the normal formats.

How to revert a merge commit that's already pushed to remote branch?

This is a very old thread, but I am missing another in my opinion convenient solution:

I never revert a merge. I just create another branch from the revision where everything was ok and then cherry pick everything that needs to picked from the old branch which was added in between.

So, if the GIT history is like this:

  • d
  • c
  • b <<< the merge
  • a
  • ...

I create a new branch from a, cherry pick c and d and then the new branch is clear from b. I can ever decide to do the merge of "b" in my new branch again. The old branch becomes deprecated and will be deleted if "b" is not necessary anymore or still in another (feature/hotfix) branch.

The only problem is now one of the very hardest things in computer science: How do you name the new branch? ;)

Ok, if you failed esp. in devel, you create newdevel as mentioned above, delete old devel and rename newdevel to devel. Mission accomplished. You can now merge the changes again when you want. It is like never merged before....

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

How can I remove a child node in HTML using JavaScript?

You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE

How do you echo a 4-digit Unicode character in Bash?

So long as your text-editors can cope with Unicode (presumably encoded in UTF-8) you can enter the Unicode code-point directly.

For instance, in the Vim text-editor you would enter insert mode and press Ctrl + V + U and then the code-point number as a 4-digit hexadecimal number (pad with zeros if necessary). So you would type Ctrl + V + U 2 6 2 0. See: What is the easiest way to insert Unicode characters into a document?

At a terminal running Bash you would type CTRL+SHIFT+U and type in the hexadecimal code-point of the character you want. During input your cursor should show an underlined u. The first non-digit you type ends input, and renders the character. So you could be able to print U+2620 in Bash using the following:

echo CTRL+SHIFT+U2620ENTERENTER

(The first enter ends Unicode input, and the second runs the echo command.)

Credit: Ask Ubuntu SE

form confirm before submit

Here's what I would do to get what you want :

$(document).ready(function() {
    $(".testform").click(function(event) {
        if( !confirm('Are you sure that you want to submit the form') ) 
            event.preventDefault();
    });
});

A slight explanation about how that code works, When the user clicks the button then the confirm dialog is launched, in case the user selects no the default action which was to submit the form is not carried out. Upon confirmation the control is passed to the browser which carries on with submitting the form. We use the standard JavaScript confirm here.

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

How to var_dump variables in twig templates?

Since Symfony >= 2.6, there is a nice VarDumper component, but it is not used by Twig's dump() function.

To overwrite it, we can create an extension:

In the following implementation, do not forget to replace namespaces.

Fuz/AppBundle/Resources/config/services.yml

parameters:
   # ...
   app.twig.debug_extension.class: Fuz\AppBundle\Twig\Extension\DebugExtension

services:
   # ...
   app.twig.debug_extension:
       class: %app.twig.debug_extension.class%
       arguments: []
       tags:
           - { name: twig.extension }

Fuz/AppBundle/Twig/Extension/DebugExtension.php

<?php

namespace Fuz\AppBundle\Twig\Extension;

class DebugExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array (
              new \Twig_SimpleFunction('dump', array('Symfony\Component\VarDumper\VarDumper', 'dump')),
        );
    }

    public function getName()
    {
        return 'FuzAppBundle:Debug';
    }

}

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

Many of them don't add this, especially in AWS EC2 Instance, I had the same issue and tried different solutions. Solution: one of my database URL inside the code was missing this parameter 'authSource', adding this worked for me.

mongodb://myUserName:MyPassword@ElasticIP:27017/databaseName?authSource=admin

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

jQuery get specific option tag text

  1. If there is only one select tag in on the page then you can specify select inside of id 'list'

    jQuery("select option[value=2]").text();
    
  2. To get selected text

    jQuery("select option:selected").text();
    

How to repeat a string a variable number of times in C++?

I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation

http://www.java-samples.com/showtutorial.php?tutorialid=458

cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;

outputs

.....lolcat

How to implement swipe gestures for mobile devices?

NOTE: Greatly inspired by EscapeNetscape's answer, I've made an edit of his script using modern javascript in a comment. I made an answer of this due to user interest and a massive 4h jsfiddle.net downtime. I chose not to edit the original answer since it would change everything...


Here is a detectSwipe function, working pretty well (used on one of my websites). I'd suggest you read it before you use it. Feel free to review it/edit the answer.

_x000D_
_x000D_
// usage example_x000D_
detectSwipe('swipeme', (el, dir) => alert(`you swiped on element with id ${el.id} to ${dir} direction`))_x000D_
_x000D_
// source code_x000D_
_x000D_
// Tune deltaMin according to your needs. Near 0 it will almost_x000D_
// always trigger, with a big value it can never trigger._x000D_
function detectSwipe(id, func, deltaMin = 90) {_x000D_
  const swipe_det = {_x000D_
    sX: 0,_x000D_
    sY: 0,_x000D_
    eX: 0,_x000D_
    eY: 0_x000D_
  }_x000D_
  // Directions enumeration_x000D_
  const directions = Object.freeze({_x000D_
    UP: 'up',_x000D_
    DOWN: 'down',_x000D_
    RIGHT: 'right',_x000D_
    LEFT: 'left'_x000D_
  })_x000D_
  let direction = null_x000D_
  const el = document.getElementById(id)_x000D_
  el.addEventListener('touchstart', function(e) {_x000D_
    const t = e.touches[0]_x000D_
    swipe_det.sX = t.screenX_x000D_
    swipe_det.sY = t.screenY_x000D_
  }, false)_x000D_
  el.addEventListener('touchmove', function(e) {_x000D_
    // Prevent default will stop user from scrolling, use with care_x000D_
    // e.preventDefault();_x000D_
    const t = e.touches[0]_x000D_
    swipe_det.eX = t.screenX_x000D_
    swipe_det.eY = t.screenY_x000D_
  }, false)_x000D_
  el.addEventListener('touchend', function(e) {_x000D_
    const deltaX = swipe_det.eX - swipe_det.sX_x000D_
    const deltaY = swipe_det.eY - swipe_det.sY_x000D_
    // Min swipe distance, you could use absolute value rather_x000D_
    // than square. It just felt better for personnal use_x000D_
    if (deltaX ** 2 + deltaY ** 2 < deltaMin ** 2) return_x000D_
    // horizontal_x000D_
    if (deltaY === 0 || Math.abs(deltaX / deltaY) > 1)_x000D_
      direction = deltaX > 0 ? directions.RIGHT : directions.LEFT_x000D_
    else // vertical_x000D_
      direction = deltaY > 0 ? directions.UP : directions.DOWN_x000D_
_x000D_
    if (direction && typeof func === 'function') func(el, direction)_x000D_
_x000D_
    direction = null_x000D_
  }, false)_x000D_
}
_x000D_
#swipeme {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: orange;_x000D_
  color: black;_x000D_
  text-align: center;_x000D_
  padding-top: 20%;_x000D_
  padding-bottom: 20%;_x000D_
}
_x000D_
<div id='swipeme'>_x000D_
  swipe me_x000D_
</div>
_x000D_
_x000D_
_x000D_

Comparing two byte arrays in .NET

It seems that EqualBytesLongUnrolled is the best from the above suggested.

Skipped methods (Enumerable.SequenceEqual,StructuralComparisons.StructuralEqualityComparer.Equals), were not-patient-for-slow. On 265MB arrays I have measured this:

Host Process Environment Information:
BenchmarkDotNet.Core=v0.9.9.0
OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-3770 CPU 3.40GHz, ProcessorCount=8
Frequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC
CLR=MS.NET 4.0.30319.42000, Arch=64-bit RELEASE [RyuJIT]
GC=Concurrent Workstation
JitModules=clrjit-v4.6.1590.0

Type=CompareMemoriesBenchmarks  Mode=Throughput  

                 Method |      Median |    StdDev | Scaled | Scaled-SD |
----------------------- |------------ |---------- |------- |---------- |
             NewMemCopy |  30.0443 ms | 1.1880 ms |   1.00 |      0.00 |
 EqualBytesLongUnrolled |  29.9917 ms | 0.7480 ms |   0.99 |      0.04 |
          msvcrt_memcmp |  30.0930 ms | 0.2964 ms |   1.00 |      0.03 |
          UnsafeCompare |  31.0520 ms | 0.7072 ms |   1.03 |      0.04 |
       ByteArrayCompare | 212.9980 ms | 2.0776 ms |   7.06 |      0.25 |

OS=Windows
Processor=?, ProcessorCount=8
Frequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC
CLR=CORE, Arch=64-bit ? [RyuJIT]
GC=Concurrent Workstation
dotnet cli version: 1.0.0-preview2-003131

Type=CompareMemoriesBenchmarks  Mode=Throughput  

                 Method |      Median |    StdDev | Scaled | Scaled-SD |
----------------------- |------------ |---------- |------- |---------- |
             NewMemCopy |  30.1789 ms | 0.0437 ms |   1.00 |      0.00 |
 EqualBytesLongUnrolled |  30.1985 ms | 0.1782 ms |   1.00 |      0.01 |
          msvcrt_memcmp |  30.1084 ms | 0.0660 ms |   1.00 |      0.00 |
          UnsafeCompare |  31.1845 ms | 0.4051 ms |   1.03 |      0.01 |
       ByteArrayCompare | 212.0213 ms | 0.1694 ms |   7.03 |      0.01 |

Warning as error - How to get rid of these

For Visual Studio Express 2013 to get rid of these problem you have to do the following.

Right click on your project click Properties. In properties window from left menus select Configuration Properties->C/C++->General

In right side select

Treat Warning As Errors NO

and

SDL Checks NO

Android: Internet connectivity change listener

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)

How to use FormData for AJAX file upload?

$('#form-withdraw').submit(function(event) {

    //prevent the form from submitting by default
    event.preventDefault();



    var formData = new FormData($(this)[0]);

    $.ajax({
        url: 'function/ajax/topup.php',
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
          if(returndata == 'success')
          {
            swal({
              title: "Great",
              text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
              type: "success",
              showCancelButton: false,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "OK",
              closeOnConfirm: false
            },
            function(){
              window.location.href = '/transaction.php';
            });
          }

          else if(returndata == 'Offline')
          {
              sweetAlert("Offline", "Please use other payment method", "error");
          }
        }
    });



}); 

..The underlying connection was closed: An unexpected error occurred on a receive

My Hosting server block requesting URL And code site getting the same error Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

enter image description here

After a lot of time spent and apply the following step to resolve this issue

  1. Added line before the call web URL

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

  2. still issue not resolve then I upgrade .net version to 4.7.2 but I think it's optional

  3. Last change I have checked my hosting server security level which causes to TLS handshaking for this used "https://www.ssllabs.com/ssltest/index.html" site
    and also check to request URL security level then I find the difference is requested URL have to enable a weak level Cipher Suites you can see in the below image

enter image description here

Now here are my hosting server supporting Cipher Suites

enter image description here

here is called if you have control over requesting URL host server then you can sync this both server Cipher Suites. but in my case, it's not possible so I have applied the following script in Windows PowerShell on my hosting server for enabling required weak level Cipher Suites.

Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_GCM_SHA384"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_GCM_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"

after applying the above script my hosting server Cipher Suites level look like

enter image description here

Then my issue resolved.

Note: server security level downgrade is not a recommended option.

Adding header for HttpURLConnection

If you are using Java 8, use the code below.

URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);

How to view file history in Git?

you could also use tig for a nice, ncurses-based git repository browser. To view history of a file:

tig path/to/file

Do something if screen width is less than 960 px

nope, none of this will work. What you need is this!!!

Try this:

if (screen.width <= 960) {
  alert('Less than 960');
} else if (screen.width >960) {
  alert('More than 960');
}

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

What does void do in java?

void means it returns nothing. It does not return a string, you write a string to System.out but you're not returning one.

You must specify what a method returns, even if you're just saying that it returns nothing.

Technically speaking they could have designed the language such that if you don't write a return type then it's assumed to return nothing, however making you explicitly write out void helps to ensure that the lack of a returned value is intentional and not accidental.

How to work with string fields in a C struct?

On strings and memory allocation:

A string in C is just a sequence of chars, so you can use char * or a char array wherever you want to use a string data type:

typedef struct     {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} patient;

Then you need to allocate memory for the structure itself, and for each of the strings:

patient *createPatient(int number, char *name, 
  char *addr, char *bd, char sex) {

  // Allocate memory for the pointers themselves and other elements
  // in the struct.
  patient *p = malloc(sizeof(struct patient));

  p->number = number; // Scalars (int, char, etc) can simply be copied

  // Must allocate memory for contents of pointers.  Here, strdup()
  // creates a new copy of name.  Another option:
  // p->name = malloc(strlen(name)+1);
  // strcpy(p->name, name);
  p->name = strdup(name);
  p->address = strdup(addr);
  p->birthdate = strdup(bd);
  p->gender = sex;
  return p;
}

If you'll only need a few patients, you can avoid the memory management at the expense of allocating more memory than you really need:

typedef struct     {
  int number;
  char name[50];       // Declaring an array will allocate the specified
  char address[200];   // amount of memory when the struct is created,
  char birthdate[50];  // but pre-determines the max length and may
  char gender;         // allocate more than you need.
} patient;

On linked lists:

In general, the purpose of a linked list is to prove quick access to an ordered collection of elements. If your llist contains an element called num (which presumably contains the patient number), you need an additional data structure to hold the actual patients themselves, and you'll need to look up the patient number every time.

Instead, if you declare

typedef struct llist
{
  patient *p;
  struct llist *next;
} list;

then each element contains a direct pointer to a patient structure, and you can access the data like this:

patient *getPatient(list *patients, int num) {
  list *l = patients;
  while (l != NULL) {
    if (l->p->num == num) {
      return l->p;
    }
    l = l->next;
  }
  return NULL;
}

Turning off auto indent when pasting text into vim

Please read this article: Toggle auto-indenting for code paste

Some people like the visual feedback shown in the status line by the following alternative for your vimrc:

nnoremap <F2> :set invpaste paste?<CR>
set pastetoggle=<F2>
set showmode

Delete item from state array in react

Use .splice to remove item from array. Using delete, indexes of the array will not be altered but the value of specific index will be undefined

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Syntax: array.splice(start, deleteCount[, item1[, item2[, ...]]])

_x000D_
_x000D_
var people = ["Bob", "Sally", "Jack"]_x000D_
var toRemove = 'Bob';_x000D_
var index = people.indexOf(toRemove);_x000D_
if (index > -1) { //Make sure item is present in the array, without if condition, -n indexes will be considered from the end of the array._x000D_
  people.splice(index, 1);_x000D_
}_x000D_
console.log(people);
_x000D_
_x000D_
_x000D_

Edit:

As pointed out by justin-grant, As a rule of thumb, Never mutate this.state directly, as calling setState() afterward may replace the mutation you made. Treat this.state as if it were immutable.

The alternative is, create copies of the objects in this.state and manipulate the copies, assigning them back using setState(). Array#map, Array#filter etc. could be used.

this.setState({people: this.state.people.filter(item => item !== e.target.value);});

Storing Form Data as a Session Variable

To use session variables, it's necessary to start the session by using the session_start function, this will allow you to store your data in the global variable $_SESSION in a productive way.

so your code will finally look like this :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // starting the session
 session_start();


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

<strong><?php echo $_SESSION['picturenum'];?></strong>

to make it easy to use and to avoid forgetting it again, you can create a session_file.php which you will want to be included in all your codes and will start the session for you:

session_start.php

 <?php
   session_start();
 ?> 

and then include it wherever you like :

<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>

<?php 
 
 // including the session file
 require_once("session_start.php");


 if (isset($_POST['Submit'])) { 
 $_SESSION['picturenum'] = $_POST['picturenum'];
 } 
?> 

that way it is more portable and easy to maintain in the future.

other remarks

  • if you are using Apache version 2 or newer, be careful. instead of
    <?
    to open php's tags, use <?php, otherwise your code will not be interpreted

  • variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters

good work!

Asynchronous shell exec in PHP

You can also run the PHP script as daemon or cronjob: #!/usr/bin/php -q

Is there a better way to run a command N times in bash?

Yet another answer: Use parameter expansion on empty parameters:

# calls curl 4 times 
curl -s -w "\n" -X GET "http:{,,,}//www.google.com"

Tested on Centos 7 and MacOS.

Filtering DataSet

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()

Java Read Large Text File With 70million line of text

I had a similar problem, but I only needed the bytes from the file. I read through links provided in the various answers, and ultimately tried writing one similar to #5 in Evgeniy's answer. They weren't kidding, it took a lot of code.

The basic premise is that each line of text is of unknown length. I will start with a SeekableByteChannel, read data into a ByteBuffer, then loop over it looking for EOL. When something is a "carryover" between loops, it increments a counter and then ultimately moves the SeekableByteChannel position around and reads the entire buffer.

It is verbose ... but it works. It was plenty fast for what I needed, but I'm sure there are more improvements that can be made.

The process method is stripped down to the basics for kicking off reading the file.

private long startOffset;
private long endOffset;
private SeekableByteChannel sbc;

private final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

public void process() throws IOException
{
    startOffset = 0;
    sbc = Files.newByteChannel(FILE, EnumSet.of(READ));
    byte[] message = null;
    while((message = readRecord()) != null)
    {
        // do something
    }
}

public byte[] readRecord() throws IOException
{
    endOffset = startOffset;

    boolean eol = false;
    boolean carryOver = false;
    byte[] record = null;

    while(!eol)
    {
        byte data;
        buffer.clear();
        final int bytesRead = sbc.read(buffer);

        if(bytesRead == -1)
        {
            return null;
        }

        buffer.flip();

        for(int i = 0; i < bytesRead && !eol; i++)
        {
            data = buffer.get();
            if(data == '\r' || data == '\n')
            {
                eol = true;
                endOffset += i;

                if(carryOver)
                {
                    final int messageSize = (int)(endOffset - startOffset);
                    sbc.position(startOffset);

                    final ByteBuffer tempBuffer = ByteBuffer.allocateDirect(messageSize);
                    sbc.read(tempBuffer);
                    tempBuffer.flip();

                    record = new byte[messageSize];
                    tempBuffer.get(record);
                }
                else
                {
                    record = new byte[i];

                    // Need to move the buffer position back since the get moved it forward
                    buffer.position(0);
                    buffer.get(record, 0, i);
                }

                // Skip past the newline characters
                if(isWindowsOS())
                {
                    startOffset = (endOffset + 2);
                }
                else
                {
                    startOffset = (endOffset + 1);
                }

                // Move the file position back
                sbc.position(startOffset);
            }
        }

        if(!eol && sbc.position() == sbc.size())
        {
            // We have hit the end of the file, just take all the bytes
            record = new byte[bytesRead];
            eol = true;
            buffer.position(0);
            buffer.get(record, 0, bytesRead);
        }
        else if(!eol)
        {
            // The EOL marker wasn't found, continue the loop
            carryOver = true;
            endOffset += bytesRead;
        }
    }

    // System.out.println(new String(record));
    return record;
}

SQL Server: the maximum number of rows in table

I do not know of a row limit, but I know tables with more than 170 million rows. You may speed it up using partitioned tables (2005+) or views that connect multiple tables.

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

Finish all previous activities

From developer.android.com:

public void finishAffinity ()

Added in API level 16

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.

Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.

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

I think that Alex Martelli's answer is definitely the most elegant way to do this, but just wanted to add a way to satisfy your want for a super awesome dictionary.filter(f) method in a Pythonic sort of way:

class FilterDict(dict):
    def __init__(self, input_dict):
        for key, value in input_dict.iteritems():
            self[key] = value
    def filter(self, criteria):
        for key, value in self.items():
            if (criteria(value)):
                self.pop(key)

my_dict = FilterDict( {'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)} )
my_dict.filter(lambda x: x[0] < 5 and x[1] < 5)

Basically we create a class that inherits from dict, but adds the filter method. We do need to use .items() for the the filtering, since using .iteritems() while destructively iterating will raise exception.

Remove Trailing Spaces and Update in Columns in SQL Server

Example:

SELECT TRIM('   Sample   ');

Result: 'Sample'

UPDATE TableName SET ColumnName = TRIM(ColumnName)

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

ffmpeg logs to stderr, and can log to a file with a different log-level from stderr. The -report command-line option doesn't give you control of the log file name or the log level, so setting the environment variable is preferable.

(-v is a synonym for -loglevel. Run ffmpeg -v help to see the levels. Run ffmpeg -h full | less to see EVERYTHING. Or consult the online docs, or their wiki pages like the h.264 encode guide).

#!/bin/bash

of=out.mkv
FFREPORT="level=32:file=$of.log" ffmpeg -v verbose   -i src.mp4 -c:a copy -preset slower -c:v libx264 -crf 21 "$of"

That will trancode src.mp4 with x264, and set the log level for stderr to "verbose", and the log level for out.mkv.log to "status".

(AV_LOG_WARNING=24, AV_LOG_INFO=32, AV_LOG_VERBOSE=40, etc.). Support for this was added 2 years ago, so you need a non-ancient version of ffmpeg. (Always a good idea anyway, for security / bugfixes and speedups)


A few codecs, like -c:v libx265, write directly to stderr instead of using ffmpeg's logging infrastructure. So their log messages don't end up in the report file. I assume this is a bug / TODO-list item.

To log stderr, while still seeing it in a terminal, you can use tee(1).


If you use a log level that includes status line updates (the default -v info, or higher), they will be included in the log file, separated with ^M (carriage return aka \r). There's no log level that includes encoder stats (like SSIM) but not status-line updates, so the best option is probably to filter that stream.

If don't want to filter (e.g. so the fps / bitrate at each status-update interval is there in the file), you can use less -r to pass them through directly to your terminal so you can view the files cleanly. If you have .enc logs from several encodes that you want to flip through, less -r ++G *.enc works great. (++G means start at the end of the file, for all files). With single-key key bindings like . and , for next file and previous file, you can flip through some log files very nicely. (the default bindings are :n and :p).

If you do want to filter, sed 's/.*\r//' works perfectly for ffmpeg output. (In the general case, you need something like vt100.py, but not for just carriage returns). There are (at least) two ways to do this with tee + sed: tee to /dev/tty and pipe tee's output into sed, or use a process substitution to tee into a pipe to sed.

# pass stdout and stderr through to the terminal, 
## and log a filtered version to a file (with only the last status-line update).

of="$1-x265.mkv"
ffmpeg -v info -i "$1" -c:a copy -c:v libx265 ... "$of" |&    # pipe stdout and stderr
   tee /dev/tty | sed 's/.*\r//' >> "$of.enc"

## or with process substitution where tee's arg will be something like /dev/fd/123

ffmpeg -v info -i "$1" -c:a copy -c:v libx265 ... "$of" |&
  tee >(sed 's/.*\r//' >> "$of.enc")

For testing a few different encode parameters, you can make a function like this one that I used recently to test some stuff. I had it all on one line so I could easily up-arrow and edit it, but I'll un-obfuscate it here. (That's why there are ;s at the end of each line)

ffenc-testclip(){
  # v should be set by the caller, to a vertical resolution.  We scale to WxH, where W is a multiple of 8 (-vf scale=-8:$v)
  db=0;   # convenient to use shell vars to encode settings that you want to include in the filename and the ffmpeg cmdline
  [email protected].${v}p.x265$pre.mkv; 
  [[ -e "$of.enc" ]]&&echo "$of.enc exists"&&return;   # early-out if the file exists

  # encode 25 seconds starting at 21m15s (or the keyframe before that)
  nice -14 ffmpeg -ss $((21*60+15))  -i src.mp4 -t 25  -map 0 -metadata title= -color_primaries bt709 -color_trc bt709 -colorspace bt709 -sws_flags lanczos+print_info -c:a copy -c:v libx265 -b:v 1500k -vf scale=-8:$v  -preset $pre -ssim 1 -x265-params ssim=1:cu-stats=1:deblock=$db:aq-mode=1:lookahead-slices=0 "$of" |&
   tee /dev/tty | sed 's/.*\r//' >> "$of.enc";
}

# and use it with nested loops like this.
for pre in fast slow;  do for v in  360 480 648 792;do  ffenc-testclip ;done;done

less -r ++G *.enc       # -r is useful if you didn't use sed

Note that it tests for existence of the output video file to avoid spewing extra garbage into the log file if it already exists. Even so, I used and append (>>) redirect.

It would be "cleaner" to write a shell function that took args instead of looking at shell variables, but this was convenient and easy to write for my own use. That's also why I saved space by not properly quoting all my variable expansions. ($v instead of "$v")

Float a div right, without impacting on design

Try setting its position to absolute. That takes it out of the flow of the document.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

I have tried every possible way to solve this issue, like ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock, uninstall and reinstall mysql, make sure mysql is running on xampp but none of it still worked.

Finally, I open up my.cnf (config file) and copy the socket path (make sure to copy the full path else it won't work). Then I perform this command in my terminal

mysql --socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

Lo, and behold, mysql launchs.

This solution will only work if your MySQL is shown running on Xampp/Ampps, but in terminal it is still not connecting to the right socket when you have already attempted something like:

./mysql -u root

or

brew services start mysql

I hope this helps!

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

require 'date'
DateTime.strptime("1318996912",'%s')

Android: How to enable/disable option menu item on button click?

If visible menu

menu.findItem(R.id.id_name).setVisible(true);

If hide menu

menu.findItem(R.id.id_name).setVisible(false);

json_encode function: special characters

you should use this code:

$json = json_encode(array_map('utf8_encode', $arr))

array_map function converts special characters in UTF8 standard

What are the differences between JSON and JSONP?

JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:

//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

The result is that you can load the JSON as a script file. If you previously set up a function called func, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:

function func(json){
  alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);

How to show text in combobox when no item selected?

Use the insert method of the combobox to insert the "Please select item" in to 0 index,

comboBox1.Items.Insert(0, "Please select any value");

and add all the items to the combobox after the first index. In the form load set

comboBox1.SelectedIndex = 0;

EDIT:

In form load write the text in to the comboBox1.Text by hardcoding

comboBox1.Text = "Please, select any value";

and in the TextChanged event of the comboBox1 write the following code

 private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex < 0)
            {
                comboBox1.Text = "Please, select any value";
            }
            else
            {
                comboBox1.Text = comboBox1.SelectedText;
            }
        }

Ring Buffer in Java

A very interesting project is disruptor. It has a ringbuffer and is used from what I know in financial applications.

See here: code of ringbuffer

I checked both Guava's EvictingQueue and ArrayDeque.

ArrayDeque does not limit growth if it's full it will double size and hence is not precisely acting like a ringbuffer.

EvictingQueue does what it promises but internally uses a Deque to store things and just bounds memory.

Hence, if you care about memory being bounded ArrayDeque is not fullfilling your promise. If you care about object count EvictingQueue uses internal composition (bigger object size).

A simple and memory efficient one can be stolen from jmonkeyengine. verbatim copy

import java.util.Iterator;
import java.util.NoSuchElementException;

public class RingBuffer<T> implements Iterable<T> {

  private T[] buffer;          // queue elements
  private int count = 0;          // number of elements on queue
  private int indexOut = 0;       // index of first element of queue
  private int indexIn = 0;       // index of next available slot

  // cast needed since no generic array creation in Java
  public RingBuffer(int capacity) {
    buffer = (T[]) new Object[capacity];
  }

  public boolean isEmpty() {
    return count == 0;
  }

  public int size() {
    return count;
  }

  public void push(T item) {
    if (count == buffer.length) {
        throw new RuntimeException("Ring buffer overflow");
    }
    buffer[indexIn] = item;
    indexIn = (indexIn + 1) % buffer.length;     // wrap-around
    count++;
  }

  public T pop() {
    if (isEmpty()) {
        throw new RuntimeException("Ring buffer underflow");
    }
    T item = buffer[indexOut];
    buffer[indexOut] = null;                  // to help with garbage collection
    count--;
    indexOut = (indexOut + 1) % buffer.length; // wrap-around
    return item;
  }

  public Iterator<T> iterator() {
    return new RingBufferIterator();
  }

  // an iterator, doesn't implement remove() since it's optional
  private class RingBufferIterator implements Iterator<T> {

    private int i = 0;

    public boolean hasNext() {
        return i < count;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return buffer[i++];
    }
  }
}

jQuery ajax success callback function definition

Try rewriting your success handler to:

success : handleData

The success property of the ajax method only requires a reference to a function.

In your handleData function you can take up to 3 parameters:

object data
string textStatus
jqXHR jqXHR

How to change context root of a dynamic web project in Eclipse?

If using maven java ee 7/8 enterprise application, need to edit the pom.xml of the EAR project

<build>
    <plugins>
        ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-ear-plugin</artifactId>
            <version>2.8</version>
            <configuration>
                <version>6</version>
                <defaultLibBundleDir>lib</defaultLibBundleDir>
                <modules>
                    <webModule>
                        <groupId>com.sample</groupId>
                        <artifactId>ProjectName-web</artifactId>
                        <contextRoot>/myproject</contextRoot>
                    </webModule>
                </modules>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

Android device chooser - My device seems offline

I fixed it by deleting unwanted applications/games from my device--make sure there is more than 15mb free space on the device.). It will work :)

Hibernate Delete query

The reason is that for deleting an object, Hibernate requires that the object is in persistent state. Thus, Hibernate first fetches the object (SELECT) and then removes it (DELETE).

Why Hibernate needs to fetch the object first? The reason is that Hibernate interceptors might be enabled (http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html), and the object must be passed through these interceptors to complete its lifecycle. If rows are delete directly in the database, the interceptor won't run.

On the other hand, it's possible to delete entities in one single SQL DELETE statement using bulk operations:

Query q = session.createQuery("delete Entity where id = X");
q.executeUpdate();

Append to the end of a Char array in C++

If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.

#include <cstring>
#include <iostream>

int main()
{
    char array1[] ="The dog jumps ";
    char array2[] = "over the log";
    char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
    std::strcpy(newArray,array1);
    std::strcat(newArray,array2);
    std::cout << newArray << std::endl;
    delete [] newArray;
    return 0;
}

This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.

Edit, a safe version with the "enough buffer space" assumption:

#include <cstring>
#include <iostream>

int main()
{
    const unsigned BUFFER_SIZE = 50;
    char array1[BUFFER_SIZE];
    std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
    char array2[] = "over the log";
    std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
    std::cout << array1 << std::endl;
    return 0;
}

How to save to local storage using Flutter?

You can use SharedPreferences for small amount of data. But if you have large and complex data then you should use Sqlite Database for local storage in flutter applications.

How to set max width of an image in CSS

You can write like this:

img{
    width:100%;
    max-width:600px;
}

Check this http://jsfiddle.net/ErNeT/

WebSockets protocol vs HTTP

You seem to assume that WebSocket is a replacement for HTTP. It is not. It's an extension.

The main use-case of WebSockets are Javascript applications which run in the web browser and receive real-time data from a server. Games are a good example.

Before WebSockets, the only method for Javascript applications to interact with a server was through XmlHttpRequest. But these have a major disadvantage: The server can't send data unless the client has explicitly requested it.

But the new WebSocket feature allows the server to send data whenever it wants. This allows to implement browser-based games with a much lower latency and without having to use ugly hacks like AJAX long-polling or browser plugins.

So why not use normal HTTP with streamed requests and responses

In a comment to another answer you suggested to just stream the client request and response body asynchronously.

In fact, WebSockets are basically that. An attempt to open a WebSocket connection from the client looks like a HTTP request at first, but a special directive in the header (Upgrade: websocket) tells the server to start communicating in this asynchronous mode. First drafts of the WebSocket protocol weren't much more than that and some handshaking to ensure that the server actually understands that the client wants to communicate asynchronously. But then it was realized that proxy servers would be confused by that, because they are used to the usual request/response model of HTTP. A potential attack scenario against proxy servers was discovered. To prevent this it was necessary to make WebSocket traffic look unlike any normal HTTP traffic. That's why the masking keys were introduced in the final version of the protocol.

PHP check if url parameter exists

Use isset()

$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.

$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

Updating state on props change in React Form

Apparently things are changing.... getDerivedStateFromProps() is now the preferred function.

_x000D_
_x000D_
class Component extends React.Component {_x000D_
  static getDerivedStateFromProps(props, current_state) {_x000D_
    if (current_state.value !== props.value) {_x000D_
      return {_x000D_
        value: props.value,_x000D_
        computed_prop: heavy_computation(props.value)_x000D_
      }_x000D_
    }_x000D_
    return null_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

(above code by danburzo @ github )

Javascript parse float is ignoring the decimals after my comma

From my origin country the currency format is like "3.050,89 €"

parseFloat identifies the dot as the decimal separator, to add 2 values we could put it like these:

parseFloat(element.toString().replace(/\./g,'').replace(',', '.'))

How to tell if a connection is dead in python

From the link Jweede posted:

exception socket.timeout:

This exception is raised when a timeout occurs on a socket
which has had timeouts enabled via a prior call to settimeout().
The accompanying value is a string whose value is currently
always “timed out”.

Here are the demo server and client programs for the socket module from the python docs

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

And the client:

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:

Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...

try:
    s.connect((HOST, PORT))
    s.send("Hello, World!")
    ...
except socket.timeout:
    # whatever you need to do when the connection is dropped

Where should I put the log4j.properties file?

You can specify config file location with VM argument -Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"

How to vertically align label and input in Bootstrap 3?

None of these solutions worked for me. But I was able to get vertical centering by using <div class="form-row align-items-center"> for each form row, per the Bootstrap examples.

How to see full absolute path of a symlink

You can use awk with a system call readlink to get the equivalent of an ls output with full symlink paths. For example:

ls | awk '{printf("%s ->", $1); system("readlink -f " $1)}'

Will display e.g.

thin_repair ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_restore ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_rmap ->/home/user/workspace/boot/usr/bin/pdata_tools
thin_trim ->/home/user/workspace/boot/usr/bin/pdata_tools
touch ->/home/user/workspace/boot/usr/bin/busybox
true ->/home/user/workspace/boot/usr/bin/busybox

Add a user control to a wpf window

Make sure there is an namespace definition (xmlns) for the namespace your control belong to.

xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>

CSS force image resize and keep aspect ratio

To force image that fit in a exact size, you don't need to write too many codes. It's so simple

_x000D_
_x000D_
img{_x000D_
    width: 200px;_x000D_
    height: auto;_x000D_
    object-fit: contain; /* Fit logo in the image size */_x000D_
        -o-object-fit: contain; /* Fit logo fro opera browser */_x000D_
    object-position: top; /* Set logo position */_x000D_
        -o-object-position: top; /* Logo position for opera browser */_x000D_
    }
_x000D_
<img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png" alt="Logo">
_x000D_
_x000D_
_x000D_

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Another option is the static String.valueOf method.

String.valueOf(i)

It feels slightly more right than Integer.toString(i) to me. When the type of i changes, for example from int to double, the code will stay correct.

'sudo gem install' or 'gem install' and gem locations

Related (for bundler users), if you want a lighter alternative to RVM which will put everything in a user-specific well known directory, I recommend using:

bundle install --path $HOME/.gem

if you want to install gems to the same place that

gem install --user-install GEMNAME

will install them, .gem/ruby/RUBYVERSION in your homedir. (See the other comment on this question about --user-install.)

This will make the gems visible to gem list, uninstallable via gem uninstall, etc. without needing sudo access. Runnable scripts installed by gem or bundler can be put into your path by adding

$HOME/.gem/ruby/RUBYVERSION/bin

to your $PATH. gem itself tells you about this if it isn't set when you do gem install --user-install.

When to use virtual destructors?

Declare destructors virtual in polymorphic base classes. This is Item 7 in Scott Meyers' Effective C++. Meyers goes on to summarize that if a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.

How to serve static files in Flask

By default folder named "static" contains all static files Here's code sample:

_x000D_
_x000D_
<link href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
_x000D_
_x000D_
_x000D_

Is it possible to use std::string in a constexpr?

No, and your compiler already gave you a comprehensive explanation.

But you could do this:

constexpr char constString[] = "constString";

At runtime, this can be used to construct a std::string when needed.

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

How to filter empty or NULL names in a QuerySet?

Firstly, the Django docs strongly recommend not using NULL values for string-based fields such as CharField or TextField. Read the documentation for the explanation:

https://docs.djangoproject.com/en/dev/ref/models/fields/#null

Solution: You can also chain together methods on QuerySets, I think. Try this:

Name.objects.exclude(alias__isnull=True).exclude(alias="")

That should give you the set you're looking for.

Is it possible to get multiple values from a subquery?

It's incorrect, but you can try this instead:

select
    a.x,
    ( select b.y from b where b.v = a.v) as by,
    ( select b.z from b where b.v = a.v) as bz
from a

you can also use subquery in join

 select
        a.x,
        b.y,
        b.z
    from a
    left join (select y,z from b where ... ) b on b.v = a.v

or

   select
        a.x,
        b.y,
        b.z
    from a
    left join b on b.v = a.v

Checkout old commit and make it a new commit

It sounds like you just want to reset to C; that is make the tree:

A-B-C

You can do that with reset:

git reset --hard HEAD~3

(Note: You said three commits ago so that's what I wrote; in your example C is only two commits ago, so you might want to use HEAD~2)


You can also use revert if you want, although as far as I know you need to do the reverts one at a time:

git revert HEAD     # Reverts E
git revert HEAD~2   # Reverts D

That will create a new commit F that's the same contents as D, and G that's the same contents as C. You can rebase to squash those together if you want

Python memory usage of numpy arrays

You can use array.nbytes for numpy arrays, for example:

>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192

batch file to check 64bit or 32bit OS

Seems to work if you do only these:

echo "%PROCESSOR_ARCHITECTURE%"

I've found these script which will do specific stuff depending of OS Architecture (x64 or x86):

@echo off
echo Detecting OS processor type

if "%PROCESSOR_ARCHITECTURE%"=="AMD64" goto 64BIT
echo 32-bit OS
\\savdaldpm01\ProtectionAgents\RA\3.0.7558.0\i386\DPMAgentInstaller_x86 /q
goto END
:64BIT
echo 64-bit OS
\\savdaldpm01\ProtectionAgents\RA\3.0.7558.0\amd64\DPMAgentInstaller_x64 /q
:END

"C:\Program Files\Microsoft Data Protection Manager\DPM\bin\setdpmserver.exe" -dpmservername sa

Try to find a way without GOTO please...

For people whom work with Unix systems, uname -m will do the trick.

How to find the logs on android studio?

My Android Studio is 3.0, please follow the two steps below,hope this will help;) First step. Second step

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

Basically you have two ways to iterate over all elements:

1. Using recursion (the most common way I think):

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    doSomething(document.getDocumentElement());
}

public static void doSomething(Node node) {
    // do something with the current node instead of System.out
    System.out.println(node.getNodeName());

    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentNode = nodeList.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            //calls this method for all the children which is Element
            doSomething(currentNode);
        }
    }
}

2. Avoiding recursion using getElementsByTagName() method with * as parameter:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));

    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            // do something with the current element
            System.out.println(node.getNodeName());
        }
    }
}

I think these ways are both efficient.
Hope this helps.

Detect if value is number in MySQL

You can use Regular Expression too... it would be like:

SELECT * FROM myTable WHERE col1 REGEXP '^[0-9]+$';

Reference: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

How to set the env variable for PHP?

You need to add the PHP directory to your path. On the command line (e.g. in a batch file), it would look like this:

SET PATH=%PATH%;C:\your\wamp\path\php

if in doubt, it's the directory containing the php.exe.

You can also pre-set the path in Windows' control panel. See here on how to do this in Windows 7 for example.

Be aware that if you call the PHP executable from an arbitrary directory, that directory will be the working directory. You may need to adjust your scripts so they use the proper directories for their file operations (if there are any).

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

Resizing image in Java

Try this:

ImageIcon icon = new ImageIcon(UrlToPngFile);
Image scaleImage = icon.getImage().getScaledInstance(28, 28,Image.SCALE_DEFAULT);

file_put_contents: Failed to open stream, no such file or directory

There is definitly a problem with the destination folder path.

Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/, which would be beyond your vhost, but somewhere in the system (see the leading absolute slash )

You should double check:

  • Is the directory /home/username/public_html/files/grantapps/ really present.
  • Contains your loop and your file_put_contents-Statement the absolute path /home/username/public_html/files/grantapps/

How to check whether input value is integer or float?

Math.round() returns the nearest integer to your given input value. If your float already has an integer value the "nearest" integer will be that same value, so all you need to do is check whether Math.round() changes the value or not:

if (value == Math.round(value)) {
  System.out.println("Integer");
} else {
  System.out.println("Not an integer");
}

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

my two cents for VS 2017:

I can confirm it works in stdafx.h both in these styles:

a)

#pragma once
#define _CRT_SECURE_NO_WARNINGS 1 
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 

b)

#define _CRT_SECURE_NO_WARNINGS 1 
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1 
#pragma once

(I have added another define for MSDN network calls..) Of course I do prefer a).

I can confirm that: #define _CRT_SECURE_NO_WARNINGS (without a value) DOES NOT WORK.

PS the real point is to put these defines BEFORE declarations of functions, i.e. before *.h

How to add column if not exists on PostgreSQL?

CREATE OR REPLACE function f_add_col(_tbl regclass, _col  text, _type regtype)
  RETURNS bool AS
$func$
BEGIN
   IF EXISTS (SELECT 1 FROM pg_attribute
              WHERE  attrelid = _tbl
              AND    attname = _col
              AND    NOT attisdropped) THEN
      RETURN FALSE;
   ELSE
      EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s', _tbl, _col, _type);
      RETURN TRUE;
   END IF;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT f_add_col('public.kat', 'pfad1', 'int');

Returns TRUE on success, else FALSE (column already exists).
Raises an exception for invalid table or type name.

Why another version?

  • This could be done with a DO statement, but DO statements cannot return anything. And if it's for repeated use, I would create a function.

  • I use the object identifier types regclass and regtype for _tbl and _type which a) prevents SQL injection and b) checks validity of both immediately (cheapest possible way). The column name _col has still to be sanitized for EXECUTE with quote_ident(). More explanation in this related answer:

  • format() requires Postgres 9.1+. For older versions concatenate manually:

    EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || quote_ident(_col) || ' ' || _type;
    
  • You can schema-qualify your table name, but you don't have to.
    You can double-quote the identifiers in the function call to preserve camel-case and reserved words (but you shouldn't use any of this anyway).

  • I query pg_catalog instead of the information_schema. Detailed explanation:

  • Blocks containing an EXCEPTION clause like the currently accepted answer are substantially slower. This is generally simpler and faster. The documentation:

Tip: A block containing an EXCEPTION clause is significantly more expensive to enter and exit than a block without one. Therefore, don't use EXCEPTION without need.

How to get relative path from absolute path

A bit late to the question, but I just needed this feature as well. I agree with DavidK that since there is a built-in API function that provides this, you should use it. Here's a managed wrapper for it:

public static string GetRelativePath(string fromPath, string toPath)
{
    int fromAttr = GetPathAttribute(fromPath);
    int toAttr = GetPathAttribute(toPath);

    StringBuilder path = new StringBuilder(260); // MAX_PATH
    if(PathRelativePathTo(
        path,
        fromPath,
        fromAttr,
        toPath,
        toAttr) == 0)
    {
        throw new ArgumentException("Paths must have a common prefix");
    }
    return path.ToString();
}

private static int GetPathAttribute(string path)
{
    DirectoryInfo di = new DirectoryInfo(path);
    if (di.Exists)
    {
        return FILE_ATTRIBUTE_DIRECTORY;
    }

    FileInfo fi = new FileInfo(path);
    if(fi.Exists)
    {
        return FILE_ATTRIBUTE_NORMAL;
    }

    throw new FileNotFoundException();
}

private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
private const int FILE_ATTRIBUTE_NORMAL = 0x80;

[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(StringBuilder pszPath, 
    string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

MetadataException: Unable to load the specified metadata resource

My theory is that if you have more than one edmx file with same name (Model1 for example), it will give that exception. I've got same problem when I decided to name all my edmx files (sitting in different projects) as Model1 because I thought they should be independent.

Want to move a particular div to right

You can use float on that particular div, e.g.

<div style="float:right;">

Float the div you want more space to have to the left as well:

<div style="float:left;">

If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

<div style="position:absolute; left:-500px; top:30px;"> 

etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

Register 32 bit COM DLL to 64 bit Windows 7

If problem not resolved, when using SysWoW64 version of regsvr32, make sure all library dependencies have same archetecture. For example, when

regsvr32 lib_x86.dll fails to register library, and %SystemRoot%\SysWow64\regsvr32 lib_x86 also fails, try to load lib_x86 to Dependency Walker application to see whole list of dependencies. If any item have 64-bit archetecture, here is the reason, why regsvr32 fails to load 32-bit library.

Understanding esModuleInterop in tsconfig file

Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

For me this error was caused by DotNetOpenAuth not being compatible with MVC5 after upgrading from MVC4 to MVC5. Uninstalling Microsoft.Web.WebPages.OAuth fixed the problem.

How to view transaction logs in SQL Server 2008

You can't read the transaction log file easily because that's not properly documented. There are basically two ways to do this. Using undocumented or semi-documented database functions or using third-party tools.

Note: This only makes sense if your database is in full recovery mode.

SQL Functions:

DBCC LOG and fn_dblog - more details here and here.

Third-party tools:

Toad for SQL Server and ApexSQL Log.

You can also check out several other topics where this was discussed:

powershell mouse move does not prevent idle mode

Try this: (source: http://just-another-blog.net/programming/powershell-and-the-net-framework/)

Add-Type -AssemblyName System.Windows.Forms 

$position = [System.Windows.Forms.Cursor]::Position  
$position.X++  
[System.Windows.Forms.Cursor]::Position = $position 

    while(1) {  
    $position = [System.Windows.Forms.Cursor]::Position  
    $position.X++  
    [System.Windows.Forms.Cursor]::Position = $position  

    $time = Get-Date;  
    $shorterTimeString = $time.ToString("HH:mm:ss");  

    Write-Host $shorterTimeString "Mouse pointer has been moved 1 pixel to the right"  
    #Set your duration between each mouse move
    Start-Sleep -Seconds 150  
    }  

How to update Xcode from command line

To those having this issue after update to Catalina, just execute this command on your terminal

sudo rm -rf /Library/Developer/CommandLineTools; xcode-select --install;

Project has no default.properties file! Edit the project properties to set one

When i imported a project from another pc into my workspace, there was the default.properties but no R.java. Editing the default.properties didnt generate R.java. I changed the skd version from 1.1 to 1.5 and the R.java file was generated and the project worked.