Programs & Examples On #Strongly typed helper

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

Remove trailing newline from the elements of a string list

>>> my_list = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> map(str.strip, my_list)
['this', 'is', 'a', 'list', 'of', 'words']

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

How do you get a query string on Flask?

from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')

Verify host key with pysftp

Try to use the 0.2.8 version of pysftp library. $ pip uninstall pysftp && pip install pysftp==0.2.8

And try with this:

try:
    ftp = pysftp.Connection(host, username=user, password=password)
 except:
    print("Couldn't connect to ftp")
    return False

Why this? Basically is a bug with the 0.2.9 of pysftp here all details https://github.com/Yenthe666/auto_backup/issues/47

HttpWebRequest using Basic authentication

Following code will solve json response if there Basic Authentication and Proxy implemented.Also IIS 7.5 Hosting Problm will resolve.

public string HttpGetByWebRequ(string uri, string username, string password)
{
//For Basic Authentication
    string authInfo = username + ":" + password;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

//For Proxy
    WebProxy proxy = new WebProxy("http://10.127.0.1:8080", true);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.Accept = "application/json; charset=utf-8";
    request.Proxy = proxy;

    request.Headers["Authorization"] = "Basic " + authInfo;

    var response = (HttpWebResponse)request.GetResponse();

    string strResponse = "";
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        strResponse= sr.ReadToEnd();

    }

    return strResponse;
}

Bootstrap Carousel image doesn't align properly

The solution is to put this CSS code into your custom CSS file:

.carousel-inner > .item > img {
  margin: 0 auto;
}

How do I clear all options in a dropdown box?

This is a bit modern and pure JavaScript

document.querySelectorAll('#selectId option').forEach(option => option.remove())

How do I center an SVG in a div?

None of these answers worked for me. This is how I did it.

position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);

How do I sort an observable collection?

I found a relevant blog entry that provides a better answer than the ones here:

http://kiwigis.blogspot.com/2010/03/how-to-sort-obversablecollection.html

UPDATE

The ObservableSortedList that @romkyns points out in the comments automatically maintains sort order.

Implements an observable collection which maintains its items in sorted order. In particular, changes to item properties that result in order changes are handled correctly.

However note also the remark

May be buggy due to the comparative complexity of the interface involved and its relatively poor documentation (see https://stackoverflow.com/a/5883947/33080).

Return row number(s) for a particular value in a column in a dataframe

Use which(mydata_2$height_chad1 == 2585)

Short example

df <- data.frame(x = c(1,1,2,3,4,5,6,3),
                 y = c(5,4,6,7,8,3,2,4))
df
  x y
1 1 5
2 1 4
3 2 6
4 3 7
5 4 8
6 5 3
7 6 2
8 3 4

which(df$x == 3)
[1] 4 8

length(which(df$x == 3))
[1] 2

count(df, vars = "x")
  x freq
1 1    2
2 2    1
3 3    2
4 4    1
5 5    1
6 6    1

df[which(df$x == 3),]
  x y
4 3 7
8 3 4

As Matt Weller pointed out, you can use the length function. The count function in plyr can be used to return the count of each unique column value.

Laravel Eloquent ORM Transactions

If you want to use Eloquent, you also can use this

This is just sample code from my project

        /* 
         * Saving Question
         */
        $question = new Question;
        $questionCategory = new QuestionCategory;

        /*
         * Insert new record for question
         */
        $question->title = $title;
        $question->user_id = Auth::user()->user_id;
        $question->description = $description;
        $question->time_post = date('Y-m-d H:i:s');

        if(Input::has('expiredtime'))
            $question->expired_time = Input::get('expiredtime');

        $questionCategory->category_id = $category;
        $questionCategory->time_added = date('Y-m-d H:i:s');

        DB::transaction(function() use ($question, $questionCategory) {

            $question->save();

            /*
             * insert new record for question category
             */
            $questionCategory->question_id = $question->id;
            $questionCategory->save();
        });

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

  1. Anything but ECB.
  2. If using CTR, it is imperative that you use a different IV for each message, otherwise you end up with the attacker being able to take two ciphertexts and deriving a combined unencrypted plaintext. The reason is that CTR mode essentially turns a block cipher into a stream cipher, and the first rule of stream ciphers is to never use the same Key+IV twice.
  3. There really isn't much difference in how difficult the modes are to implement. Some modes only require the block cipher to operate in the encrypting direction. However, most block ciphers, including AES, don't take much more code to implement decryption.
  4. For all cipher modes, it is important to use different IVs for each message if your messages could be identical in the first several bytes, and you don't want an attacker knowing this.

Modify tick label text

Caveat: Unless the ticklabels are already set to a string (as is usually the case in e.g. a boxplot), this will not work with any version of matplotlib newer than 1.1.0. If you're working from the current github master, this won't work. I'm not sure what the problem is yet... It may be an unintended change, or it may not be...

Normally, you'd do something along these lines:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# We need to draw the canvas, otherwise the labels won't be positioned and 
# won't have values yet.
fig.canvas.draw()

labels = [item.get_text() for item in ax.get_xticklabels()]
labels[1] = 'Testing'

ax.set_xticklabels(labels)

plt.show()

enter image description here

To understand the reason why you need to jump through so many hoops, you need to understand a bit more about how matplotlib is structured.

Matplotlib deliberately avoids doing "static" positioning of ticks, etc, unless it's explicitly told to. The assumption is that you'll want to interact with the plot, and so the bounds of the plot, ticks, ticklabels, etc will be dynamically changing.

Therefore, you can't just set the text of a given tick label. By default, it's re-set by the axis's Locator and Formatter every time the plot is drawn.

However, if the Locators and Formatters are set to be static (FixedLocator and FixedFormatter, respectively), then the tick labels stay the same.

This is what set_*ticklabels or ax.*axis.set_ticklabels does.

Hopefully that makes it slighly more clear as to why changing an individual tick label is a bit convoluted.

Often, what you actually want to do is just annotate a certain position. In that case, look into annotate, instead.

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

XAMPP Port 80 in use by "Unable to open process" with PID 4

Your port 80 is being used by the system.

  1. In Windows “World Wide Publishing" Service is using this port and it's process is system which PID is 4 maximum time and stopping this service(“World Wide Publishing") will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop.
  2. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
  3. If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

bash: npm: command not found?

The solution is simple.

After installing Node, you should restart your VScode and run npm install command.

How do I vertically center text with CSS?

You can easily do this by adding the following piece of CSS code:

display: table-cell;
vertical-align: middle;

That means your CSS finally looks like:

_x000D_
_x000D_
#box {_x000D_
  height: 90px;_x000D_
  width: 270px;_x000D_
  background: #000;_x000D_
  font-size: 48px;_x000D_
  font-style: oblique;_x000D_
  color: #FFF;_x000D_
  text-align: center;_x000D_
  margin-top: 20px;_x000D_
  margin-left: 5px;_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div id="box">_x000D_
  Some text_x000D_
</div>
_x000D_
_x000D_
_x000D_

Git commit with no commit message

--allow-empty-message -m '' (and -m "") fail in Git 2.29.2 on PowerShell:

error: switch `m' requires a value

(oddly enough, with a backtick on one side and a single quote on the other)


The following works consistently in Linux, PowerShell, and Command Prompt:

git commit --allow-empty-message --no-edit

The --no-edit bit does the trick, as it prevents the editor from launching.

I find this form more explicit and a bit less hacky than forcing an empty message with -m ''.

How to get visitor's location (i.e. country) using geolocation?

You can use my service, http://ipinfo.io, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here's a simple example that logs the city and country:

$.get("https://ipinfo.io", function(response) {
    console.log(response.city, response.country);
}, "jsonp");

Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/

The location will generally be less accurate than the native geolocation details, but it doesn't require any user permission.

Open a new tab in the background?

UPDATE: By version 41 of Google Chrome, initMouseEvent seemed to have a changed behavior.

this can be done by simulating ctrl + click (or any other key/event combinations that open a background tab) on a dynamically generated a element with its href attribute set to the desired url

In action: fiddle

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = "http://www.google.com/";
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

tested only on chrome

Radio buttons not checked in jQuery

If my firebug profiler work fine (and i know how to use it well), this:

$('#communitymode').attr('checked')

is faster than

$('#communitymode').is('checked')

You can try on this page :)

And then you can use it like

if($('#communitymode').attr('checked')===true) { 
// do something
}

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

u should add a theme to ur all activities (u should add theme for all application in ur <application> in ur manifest) but if u have set different theme to ur activity u can use :

 android:theme="@style/Theme.AppCompat"

or each kind of AppCompat theme!

What is the best project structure for a Python application?

The "Python Packaging Authority" has a sampleproject:

https://github.com/pypa/sampleproject

It is a sample project that exists as an aid to the Python Packaging User Guide's Tutorial on Packaging and Distributing Projects.

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

Wordpress plugin install: Could not create directory

I had to give ownership of /plugins and /upgrade to the server, nothing else.

$ cd /var/www/wordpress/wp-content
$ sudo chown www-data:www-data /plugings
$ sudo chown www-data:www-data /upgrade

Running Apache server on Ubuntu 18.04. Maybe more dirs will need to be changed later. Anyways, I plan to restore permissions once I finish editing, as suggested in this anwser.

R: "Unary operator error" from multiline ggplot2 command

It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.

This works:

ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot() 

The does not:

ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot() 

*Error in + geom_boxplot():
invalid argument to unary operator*

You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.

Returning the product of a list

if you just have numbers in your list:

from numpy import prod
prod(list)

EDIT: as pointed out by @off99555 this does not work for large integer results in which case it returns a result of type numpy.int64 while Ian Clelland's solution based on operator.mul and reduce works for large integer results because it returns long.

Sublime Text 2: How to delete blank/empty lines

If ^\n does not work properly ===> try .*[^\w]\n

In a simple to understand explanation, what is Runnable in Java?

Runnable is an interface defined as so:

interface Runnable {
    public void run();
}

To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {

It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.

If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.

It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.

How to find when a web page was last updated

For me it was the

article:modified_time

in the page source.

View Page Source

Remove border from IFrame

To remove border you can use CSS border property to none.

<iframe src="myURL" width="300" height="300" style="border: none">Browser not compatible.</iframe>

How to encode URL to avoid special characters in Java?

If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec

String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);

How to compile Tensorflow with SSE4.2 and AVX instructions?

Let me answer your 3rd question first:

If you want to run a self-compiled version within a conda-env, you can. These are the general instructions I run to get tensorflow to install on my system with additional instructions. Note: This build was for an AMD A10-7850 build (check your CPU for what instructions are supported...it may differ) running Ubuntu 16.04 LTS. I use Python 3.5 within my conda-env. Credit goes to the tensorflow source install page and the answers provided above.

git clone https://github.com/tensorflow/tensorflow 
# Install Bazel
# https://bazel.build/versions/master/docs/install.html
sudo apt-get install python3-numpy python3-dev python3-pip python3-wheel
# Create your virtual env with conda.
source activate YOUR_ENV
pip install six numpy wheel, packaging, appdir
# Follow the configure instructions at:
# https://www.tensorflow.org/install/install_sources
# Build your build like below. Note: Check what instructions your CPU 
# support. Also. If resources are limited consider adding the following 
# tag --local_resources 2048,.5,1.0 . This will limit how much ram many
# local resources are used but will increase time to compile.
bazel build -c opt --copt=-mavx --copt=-msse4.1 --copt=-msse4.2  -k //tensorflow/tools/pip_package:build_pip_package
# Create the wheel like so:
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
# Inside your conda env:
pip install /tmp/tensorflow_pkg/NAME_OF_WHEEL.whl
# Then install the rest of your stack
pip install keras jupyter etc. etc.

As to your 2nd question:

A self-compiled version with optimizations are well worth the effort in my opinion. On my particular setup, calculations that used to take 560-600 seconds now only take about 300 seconds! Although the exact numbers will vary, I think you can expect about a 35-50% speed increase in general on your particular setup.

Lastly your 1st question:

A lot of the answers have been provided above already. To summarize: AVX, SSE4.1, SSE4.2, MFA are different kinds of extended instruction sets on X86 CPUs. Many contain optimized instructions for processing matrix or vector operations.

I will highlight my own misconception to hopefully save you some time: It's not that SSE4.2 is a newer version of instructions superseding SSE4.1. SSE4 = SSE4.1 (a set of 47 instructions) + SSE4.2 (a set of 7 instructions).

In the context of tensorflow compilation, if you computer supports AVX2 and AVX, and SSE4.1 and SSE4.2, you should put those optimizing flags in for all. Don't do like I did and just go with SSE4.2 thinking that it's newer and should superseed SSE4.1. That's clearly WRONG! I had to recompile because of that which cost me a good 40 minutes.

What's the u prefix in a Python string?

All strings meant for humans should use u"".

I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u"" syntax. The "" syntax is for byte arrays, only.

Before the bashing begins, let me explain. Most Python programs start out with using "" for strings. But then they need to support documentation off the Internet, so they start using "".decode and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of "" for strings. In this case, Unicode does act like a virus and will wreak havoc.

But, if you follow my rule, you won't have this infection (because you will already be infected).

Create a OpenSSL certificate on Windows

Consider using certificate depot web app to easily create private key and certificate based on it: http://www.cert-depot.com/

It can also create a PFX for you.

Disclaimer: I am the creator of certificate depot.

Inner Joining three tables

try the following code

select * from TableA A 
inner join TableB B on A.Column=B.Column 
inner join TableC C on A.Column=C.Column

How to round a number to significant figures in Python

If you want to round without involving strings, the link I found buried in the comments above:

http://code.activestate.com/lists/python-tutor/70739/

strikes me as best. Then when you print with any string formatting descriptors, you get a reasonable output, and you can use the numeric representation for other calculation purposes.

The code at the link is a three liner: def, doc, and return. It has a bug: you need to check for exploding logarithms. That is easy. Compare the input to sys.float_info.min. The complete solution is:

import sys,math

def tidy(x, n):
"""Return 'x' rounded to 'n' significant digits."""
y=abs(x)
if y <= sys.float_info.min: return 0.0
return round( x, int( n-math.ceil(math.log10(y)) ) )

It works for any scalar numeric value, and n can be a float if you need to shift the response for some reason. You can actually push the limit to:

sys.float_info.min*sys.float_info.epsilon

without provoking an error, if for some reason you are working with miniscule values.

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

How can I find the number of years between two dates?

This will work and if you want the number of years replace 12 to 1

    String date1 = "07-01-2015";
    String date2 = "07-11-2015";
    int i = Integer.parseInt(date1.substring(6));
    int j = Integer.parseInt(date2.substring(6));
    int p = Integer.parseInt(date1.substring(3,5));
    int q = Integer.parseInt(date2.substring(3,5));


    int z;
    if(q>=p){
        z=q-p + (j-i)*12;
    }else{
        z=p-q + (j-i)*12;
    }
    System.out.println("The Total Months difference between two dates is --> "+z+" Months");

SQL Server query to find all current database names

Another to add to the mix:

EXEC sp_databases

How do I get a python program to do nothing?

you can use pass inside if statement.

Call a python function from jinja2

Use a lambda to connect the template to your main code

return render_template("clever_template", clever_function=lambda x: clever_function x)

Then you can seamlessly call the function in the template

{{clever_function(value)}}

How do I create a GUI for a windows application using C++?

A simple "window" with some text and a button is just a MessageBox. You can create them with a single function call; you don't need any library whatsoever.

calling parent class method from child class object in java

Say the hierarchy is C->B->A with A being the base class.

I think there's more to fixing this than renaming a method. That will work but is that a fix?

One way is to refactor all the functionality common to B and C into D, and let B and C inherit from D: (B,C)->D->A Now the method in B that was hiding A's implementation from C is specific to B and stays there. This allows C to invoke the method in A without any hokery.

Limiting Python input strings to certain characters and lengths

We can use assert here.

def _input(inp_str:str):
    try:
        assert len(inp_str)<=15,print('More than 15 characters present')
        assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
        return inp_str
    except Exception as e:
        pass

_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present

What is Ruby's double-colon `::`?

What good is scope (private, protected) if you can just use :: to expose anything?

In Ruby, everything is exposed and everything can be modified from anywhere else.

If you're worried about the fact that classes can be changed from outside the "class definition", then Ruby probably isn't for you.

On the other hand, if you're frustrated by Java's classes being locked down, then Ruby is probably what you're looking for.

Arrays in cookies PHP

Just found the thing needed. Now, I can store products visited on cookies and show them later when they get back to the site.

// set the cookies
setcookie("product[cookiethree]", "cookiethree");
setcookie("product[cookietwo]", "cookietwo");
setcookie("product[cookieone]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['product'])) {
    foreach ($_COOKIE['product'] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}

Oracle date function for the previous month

It is working with me in Oracle sql developer

    SELECT add_months(trunc(sysdate,'mm'), -1),
           last_day(add_months(trunc(sysdate,'mm'), -1)) 
    FROM dual

The given key was not present in the dictionary. Which key?

This exception is thrown when you try to index to something that isn't there, for example:

Dictionary<String, String> test = new Dictionary<String,String>();
test.Add("Key1","Value1");
string error = test["Key2"];

Often times, something like an object will be the key, which undoubtedly makes it harder to get. However, you can always write the following (or even wrap it up in an extension method):

if (test.ContainsKey(myKey))
   return test[myKey];
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Or more efficient (thanks to @ScottChamberlain)

T retValue;
if (test.TryGetValue(myKey, out retValue))
    return retValue;
else
   throw new Exception(String.Format("Key {0} was not found", myKey));

Microsoft chose not to do this, probably because it would be useless when used on most objects. Its simple enough to do yourself, so just roll your own!

How to change folder with git bash?

just right click on the desired folder and select git-bash Here option it will direct you to that folder and start working hope it will work.

How to keep a VMWare VM's clock in sync?

Something to note here. We had the same issue with Windows VM's running on an ESXi host. The time sync was turned on in VMWare Tools on the guest, but the guest clocks were consistently off (by about 30 seconds) from the host clock. The ESXi host was configured to get time updates from an internal time server.

It turns out we had the Internet Time setting turned on in the Windows VM's (Control Panel > Date and Time > Internet Time tab) so the guest was getting time updates from two places and the internet time was winning. We turned that off and now the guest clocks are good, getting their time exclusively from the ESXi host.

Switch case with conditions

Switch case is every help full instead of if else statement :

     switch ($("[id*=btnSave]").val()) {
        case 'Search':
            saveFlight();
            break;
        case 'Update':
            break;
        case 'Delete':
            break;
        default:
            break;
    }

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

How do I load a PHP file into a variable?

Theoretically you could just use fopen, then use stream_get_contents.

$stream = fopen("file.php","r");
$string = stream_get_contents($stream);
fclose($stream);

That should read the entire file into $string for you, and should not evaluate it. Though I'm surprised that file_get_contents didn't work when you specified the local path....

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

How to prevent a browser from storing passwords

I solved this by adding autocomplete="one-time-code" to the password input.

As per an HTML reference autocomplete="one-time-code" - a one-time code used for verifying user identity. It looks like the best fit for this.

Sorting list based on values from another list

Also, if you don't mind using numpy arrays (or in fact already are dealing with numpy arrays...), here is another nice solution:

people = ['Jim', 'Pam', 'Micheal', 'Dwight']
ages = [27, 25, 4, 9]

import numpy
people = numpy.array(people)
ages = numpy.array(ages)
inds = ages.argsort()
sortedPeople = people[inds]

I found it here: http://scienceoss.com/sort-one-list-by-another-list/

How do I round a float upwards to the nearest int in C#?

You can cast to an int provided you are sure it's in the range for an int (Int32.MinValue to Int32.MaxValue).

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

java.util.zip.ZipException: error in opening zip file

In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.

Writing a pandas DataFrame to CSV file

it could be not the answer for this case, but as I had the same error-message with .to_csvI tried .toCSV('name.csv') and the error-message was different ("SparseDataFrame' object has no attribute 'toCSV'). So the problem was solved by turning dataframe to dense dataframe

df.to_dense().to_csv("submission.csv", index = False, sep=',', encoding='utf-8')

Reading RFID with Android phones

NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.

You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.

I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.

If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.

How to spyOn a value property (rather than a method) with Jasmine

The right way to do this is with the spy on property, it will allow you to simulate a property on an object with an specific value.

const spy = spyOnProperty(myObj, 'valueA').and.returnValue(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();

Accessing Google Account Id /username via Android

if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
  Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
  String userid=currentPerson.getId(); //BY THIS CODE YOU CAN GET CURRENT LOGIN USER ID
}

How to create a circle icon button in Flutter?

You can also use a RaisedButton with an image inside (for example for social login) like this (sizedbox with fittebox is needed to contraint the image on the specified size):

FittedBox(
    fit: BoxFit.scaleDown,
    child: SizedBox(
        height: 60,
        width: 60,
        child: RaisedButton(
             child: Image.asset(
                 'assets/images/google_logo.png'),
                 shape: StadiumBorder(),
                 color: Colors.white,
                     onPressed: () {},
                 ),
             ),
         ),

How to align texts inside of an input?

The accepted answer here is correct but I'd like to add a little info. If you are using a library / framework like bootstrap there may be built in classes for this. For example bootstrap uses the text-right class. Use it like this:

<input type="text" class="text-right"/> 
<input type="number" class="text-right"/>

As a note this works on other input types as well, like numeric as shown above.

If you aren't using a nice framework like bootstrap then you can make your own version of this helper class. Similar to other answers but we are not going to add it directly to the input class so it won't apply to every single input on your site or page, this might not be desired behavior. So this would create a nice easy css class to align things right without needing inline styling or affecting every single input box.

.text-right{
    text-align: right;
}

Now you can use this class exactly the same as the inputs above with class="text-right". I know it isn't saving that many key strokes but it makes your code cleaner.

PHP, getting variable from another php-file

You could also use a session for passing small bits of info. You will need to have session_start(); at the top of the PHP pages that use the session else the variables will not be accessable

page1.php

<?php

   session_start();
   $_SESSION['superhero'] = "batman";

?>
<a href="page2.php" title="">Go to the other page</a>

page2.php

<?php 

   session_start(); // this NEEDS TO BE AT THE TOP of the page before any output etc
   echo $_SESSION['superhero'];

?>

How to get the Facebook user id using the access token

Check out this answer, which describes, how to get ID response. First, you need to create method get data:

const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
    const options = {
        host: 'graph.facebook.com',
        port: 443,
        path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
        method: 'GET'
    };

    let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
    const request = https.get(options, (result) => {
        result.setEncoding('utf8');
        result.on('data', (chunk) => {
            buffer += chunk;
        });

        result.on('end', () => {
            callback(buffer);
        });
    });

    request.on('error', (e) => {
        console.log(`error from facebook.getFbData: ${e.message}`)
    });

    request.end();
}

Then simply use your method whenever you want, like this:

getFbData(access_token, '/me?fields=id&', (result) => {
      console.log(result);
});

error: command 'gcc' failed with exit status 1 while installing eventlet

This page is gonna save your life, for all further lib issues that are forthcoming,

For Alpine(>=3.6),

use apk --update --upgrade add gcc musl-dev jpeg-dev zlib-dev libffi-dev cairo-dev pango-dev gdk-pixbuf-dev

How to make a function wait until a callback has been called using node.js

Since node 4.8.0 you are able to use the feature of ES6 called generator. You may follow this article for deeper concepts. But basically you can use generators and promises to get this job done. I'm using bluebird to promisify and manage the generator.

Your code should be fine like the example below.

const Promise = require('bluebird');

function* getResponse(query) {
  const r = yield new Promise(resolve => myApi.exec('SomeCommand', resolve);
  return r;
}

Promise.coroutine(getResponse)()
  .then(response => console.log(response));

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

What's the best way to add a full screen background image in React Native

If you want to use it as a background image, you will need to use the new <ImageBackground> component introduced at the end of June 2017 in v0.46. It supports nesting while <Image> soon won't.

Here is the commit summary:

We are removing support of nesting views inside component. We decided to do this because having this feature makes supporting intrinsinc content size of the <Image> impossible; so when the transition process is complete, there will be no need to specify image size explicitly, it can be inferred from actual image bitmap.

And this is the step #0.

is very simple drop-in replacement which implements this functionality via very simple styling. Please, use instead of if you want to put something inside.

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

If you add files that are too large (GBs in my case, Cygwin, XP, 3 GB RAM), expect this.

fatal: Out of memory, malloc failed

More details here

Update 3/2/11: Saw similar in Windows 7 x64 with Tortoise Git. Tons of memory used, very very slow system response.

Remove a file from the list that will be committed

Use stash; like this:

git add .
git reset Files/I/Want/To/Keep
git stash --keep-index
git commit -a -m "Done!"
git stash pop

If you accidentally commit a file, and want to rewrite your git history, use:

git reset HEAD~1 path/to/file
git commit -a -m "rollback"
git rebase -i HEAD~2

and squash to the two leading commits. You can write a helper script to do either of these if you have a known set of files you prefer not to automatically commit.

How to find index of STRING array in Java from a given value?

Try this Function :

public int indexOfArray(String input){
     for(int i=0;i<TYPES,length();i++)
       {
         if(TYPES[i].equals(input))
         {
          return i ;
         }
        }
      return -1     // if the text not found the function return -1
      }

How to access global variables

I create a file dif.go that contains your code:

package dif

import (
    "time"
)

var StartTime = time.Now()

Outside the folder I create my main.go, it is ok!

package main

import (
    dif "./dif"
    "fmt"
)

func main() {
    fmt.Println(dif.StartTime)
}

Outputs:

2016-01-27 21:56:47.729019925 +0800 CST

Files directory structure:

folder
  main.go
  dif
    dif.go

It works!

Instantly detect client disconnection from server socket

Someone mentioned keepAlive capability of TCP Socket. Here it is nicely described:

http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html

I'm using it this way: after the socket is connected, I'm calling this function, which sets keepAlive on. The keepAliveTime parameter specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent. The keepAliveInterval parameter specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received.

    void SetKeepAlive(bool on, uint keepAliveTime, uint keepAliveInterval)
    {
        int size = Marshal.SizeOf(new uint());

        var inOptionValues = new byte[size * 3];

        BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
        BitConverter.GetBytes((uint)keepAliveTime).CopyTo(inOptionValues, size);
        BitConverter.GetBytes((uint)keepAliveInterval).CopyTo(inOptionValues, size * 2);

        socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
    }

I'm also using asynchronous reading:

socket.BeginReceive(packet.dataBuffer, 0, 128,
                    SocketFlags.None, new AsyncCallback(OnDataReceived), packet);

And in callback, here is caught timeout SocketException, which raises when socket doesn't get ACK signal after keep-alive packet.

public void OnDataReceived(IAsyncResult asyn)
{
    try
    {
        SocketPacket theSockId = (SocketPacket)asyn.AsyncState;

        int iRx = socket.EndReceive(asyn);
    }
    catch (SocketException ex)
    {
        SocketExceptionCaught(ex);
    }
}

This way, I'm able to safely detect disconnection between TCP client and server.

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

Use Fieldset Legend with bootstrap

Just wanted to summarize all the correct answers above in short. Because I had to spend lot of time to figure out which answer resolves the issue and what's going on behind the scenes.

There seems to be two problems of fieldset with bootstrap:

  1. The bootstrap sets the width to the legend as 100%. That is why it overlays the top border of the fieldset.
  2. There's a bottom border for the legend.

So, all we need to fix this is set the legend width to auto as follows:

legend.scheduler-border {
   width: auto; // fixes the problem 1
   border-bottom: none; // fixes the problem 2
}

Conversion hex string into ascii in bash command line

The echo -e must have been failing for you because of wrong escaping. The following code works fine for me on a similar output from your_program with arguments:

echo -e $(your_program with arguments | sed -e 's/0x\(..\)\.\?/\\x\1/g')

Please note however that your original hexstring consists of non-printable characters.

What's the best way to use R scripts on the command line (terminal)?

Try littler. littler provides hash-bang (i.e. script starting with #!/some/path) capability for GNU R, as well as simple command-line and piping use.

What is the difference between mocking and spying when using Mockito?

Difference between a Spy and a Mock

When Mockito creates a mock – it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance – the only difference is that it will also be instrumented to track all the interactions with it.

In the following example – we create a mock of the ArrayList class:

@Test
public void whenCreateMock_thenCreated() {
    List mockedList = Mockito.mock(ArrayList.class);

    mockedList.add("one");
    Mockito.verify(mockedList).add("one");

    assertEquals(0, mockedList.size());
}

As you can see – adding an element into the mocked list doesn’t actually add anything – it just calls the method with no other side-effect. A spy on the other hand will behave differently – it will actually call the real implementation of the add method and add the element to the underlying list:

@Test
public void whenCreateSpy_thenCreate() {
    List spyList = Mockito.spy(new ArrayList());
    spyList.add("one");
    Mockito.verify(spyList).add("one");

    assertEquals(1, spyList.size());
}

Here we can surely say that the real internal method of the object was called because when you call the size() method you get the size as 1, but this size() method isn’t been mocked! So where does 1 come from? The internal real size() method is called as size() isn’t mocked (or stubbed) and hence we can say that the entry was added to the real object.

Source: http://www.baeldung.com/mockito-spy + self notes.

How to extract a single value from JSON response?

Extract single value from JSON response Python

Try this

import json
import sys

#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

#print the resp
print (resp)

#extract an element in the response
print (resp['test1'])

How to replace � in a string

That's the Unicode Replacement Character, \uFFFD. (info)

Something like this should work:

String strImport = "For some reason my ?double quotes? were lost.";
strImport = strImport.replaceAll("\uFFFD", "\"");

Collections.emptyList() vs. new instance

Use Collections.emptyList() if you want to make sure that the returned list is never modified.

This is what is returned on calling emptyList():

/**
 * The empty list (immutable). 
 */
public static final List EMPTY_LIST = new EmptyList();

Calculate time difference in minutes in SQL Server

You can use DATEDIFF(it is a built-in function) and % (for scale calculation) and CONCAT for make result to only one column

select CONCAT('Month: ',MonthDiff,' Days: ' , DayDiff,' Minutes: ',MinuteDiff,' Seconds: ',SecondDiff) as T  from 
(SELECT DATEDIFF(MONTH, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 12 as MonthDiff,
        DATEDIFF(DAY, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 30 as DayDiff,
        DATEDIFF(HOUR, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 24 as HourDiff,
        DATEDIFF(MINUTE, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS MinuteDiff,
        DATEDIFF(SECOND, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS SecondDiff) tbl

POSTing JsonObject With HttpClient From Web API

I don't have enough reputation to add a comment on the answer from pomber so I'm posting another answer. Using pomber's approach I kept receiving a "400 Bad Request" response from an API I was POSTing my JSON request to (Visual Studio 2017, .NET 4.6.2). Eventually the problem was traced to the "Content-Type" header produced by StringContent() being incorrect (see https://github.com/dotnet/corefx/issues/7864).

tl;dr

Use pomber's answer with an extra line to correctly set the header on the request:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

For Windows, you can check the official Intel MKL optimization for TensorFlow wheels that are compiled with AVX2. This solution speeds up my inference ~x3.

conda install tensorflow-mkl

powershell - list local users and their groups

Use this to get an array with the local users and the groups they are member of:

Get-LocalUser | 
    ForEach-Object { 
        $user = $_
        return [PSCustomObject]@{ 
            "User"   = $user.Name
            "Groups" = Get-LocalGroup | Where-Object {  $user.SID -in ($_ | Get-LocalGroupMember | Select-Object -ExpandProperty "SID") } | Select-Object -ExpandProperty "Name"
        } 
    }

To get an array with the local groups and their members:

Get-LocalGroup | 
    ForEach-Object {
        $group = $_
        return [PSCustomObject]@{ 
            "Group"   = $group.Name
            "Members" = $group | Get-LocalGroupMember | Select-Object -ExpandProperty "Name"
        } 
    } 

Case insensitive string as HashMap key

As suggested by Guido García in their answer here:

import java.util.HashMap;

public class CaseInsensitiveMap extends HashMap<String, String> {

    @Override
    public String put(String key, String value) {
       return super.put(key.toLowerCase(), value);
    }

    // not @Override because that would require the key parameter to be of type Object
    public String get(String key) {
       return super.get(key.toLowerCase());
    }
}

Or

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/CaseInsensitiveMap.html

Requery a subform from another form?

I had a similar kind of issue, but with some differences...

In my case, my main form has a Control (vendor) which value I used to update a Query in my DB, using the following code:

Sub Set_Qry_PedidosRealizadosImportados_frm(Vd As Long)
Dim temp_qry As DAO.QueryDef

'Procedimento para ajustar o codigo do cliente na Qry_Pedidos realizados e importados
'Procedure to adjust the code of the client on Qry_Pedidos realizados e importados
Set temp_qry = CurrentDb.QueryDefs("Qry_Pedidos realizados e importados")
temp_qry.SQL = "SELECT DISTINCT " & _
            "[Qry_Pedidos distintos].[Codigo], " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "COUNT([Qry_Pedidos distintos].[Pedido Avante]) As [Pedidos realizados], " & _
            "SUM(IIf(NZ([Qry_Pedidos distintos].[Pedido Flexx], 0) > 1, 1, 0)) As [Pedidos Importados] " & _
            "FROM [Qry_Pedidos distintos] " & _
            "WHERE [Qry_Pedidos distintos].Vd = " & Vd & _
            " Group BY " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "[Qry_Pedidos distintos].[Codigo];"
End Sub

Since the beginning my subform record source was the query named "Qry_Pedidos realizados e importados".

But the only way I could update the subform data inside the main form context was to refresh the data source of the subform to it self, like posted bellow:

Private Sub cmb_vendedor_v1_Exit(Cancel As Integer)
'Codigo para atualizar o comando SQL da query
'Code to update the SQL statement of the query 
    Call Set_Qry_Pedidosrealizadosimportados_frm(Me.cmb_vendedor_v1.Value)

'Codigo para forçar o Access a aceitar o novo comando SQL
'Code to force de Access to accept the new sql statement
    Me!Frm_Pedidos_realizados_importados.Form.RecordSource = "Qry_Pedidos realizados e importados"
End Sub

No refresh, recalc, requery, etc, was necessary after all...

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

My issue resolve via following Steps

  1. File->Import (android-sdk\extras\android\support\v7\appcompat)

  2. Right Click Project-> properties->Android. In the section library "Add" and choose library appcompat that's include in step 1

  3. Delete all files from project's libs directory

  4. add following file to project's libs directory <SDK-PATH>\extras\android\support\v13android-support-v13.jar

    Restart Eclipse if required. That's it. Your problem should be disappeared.

How to install PyQt5 on Windows?

The easiest way to install PyQt is to just use the installer (Link in your answer, step #5). If you install python 3.3, the installer will add all of the PyQt5 extras to that python installation automatically. You won't need to do any compiling (none of: nmake, nmake install, python configure).

All of the build options are available for if you need a custom install (for instance, using a different version of python, where there isn't an installer provided by riverbank computing).

If you do need to compile your own version of PyQt5, the steps (as you have found) are here, but assume you have python and a compiler installed and in your path. The installed and in your path have been where you have been running into trouble it seems. I'd recommend using the installer version, but you need to install python 3.3 first.

Could not find or load main class

i had

':'

in my project name e.g 'HKUSTx:part-2' renaming it 'HKUSTx-part-2' worked for me

Adding an image to a PDF using iTextSharp and scale it properly

You can try something like this:

      Image logo = Image.GetInstance("pathToTheImage")
      logo.ScaleAbsolute(500, 300)

CSS border less than 1px

It's impossible to draw a line on screen that's thinner than one pixel. Try using a more subtle color for the border instead.

Default Activity not found in Android Studio

Following did the trick for me. From Run -> Edit Configuration.

enter image description here

don't fail jenkins build if execute shell fails

This answer is correct, but it doesn't specify the || exit 0 or || true goes inside the shell command. Here's a more complete example:

sh "adb uninstall com.example.app || true"

The above will work, but the following will fail:

sh "adb uninstall com.example.app" || true

Perhaps it's obvious to others, but I wasted a lot of time before I realized this.

How to represent multiple conditions in a shell if statement?

Using /bin/bash the following will work:

if [ "$option" = "Y" ] || [ "$option" = "y" ]; then
    echo "Entered $option"
fi

Build a simple HTTP server in C

Look at nweb (Nigel's Web Server), "a tiny, safe web server [...] with only 200 lines of C source code":

https://drive.google.com/file/d/0B3msld7qnNOhN1NXaFIwSFU2Mjg/view?usp=sharing http://www.ibm.com/developerworks/systems/library/es-nweb/

The article includes pseudocode, explanations, and comments.

EDIT: IBM's link has died. I have saved a PDF of the webpage to Google Drive. Here is the code download:

https://drive.google.com/file/d/0B3msld7qnNOhSGZGdDJJMmY0VHM/view?usp=sharing

@ankushagarwal has made a few changes and uploaded his version on GitHub: https://github.com/ankushagarwal/nweb

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

Android get current Locale, not default

If you are using the Android Support Library you can use ConfigurationCompat instead of @Makalele's method to get rid of deprecation warnings:

Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);

or in Kotlin:

val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]

Send email using the GMail SMTP server from a PHP page

I don't recommend Pear Mail. It has not been updated since 2010. Also read the source files; the source code is almost outdated, written in PHP 4 style and many errors / bugs have been posted (Google it). I am using Swift Mailer.

Swift Mailer integrates into any web application written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.

Send emails using SMTP, sendmail, postfix or a custom Transport implementation of your own.

Support servers that require username & password and/or encryption.

Protect from header injection attacks without stripping request data content.

Send MIME compliant HTML/multipart emails.

Use event-driven plugins to customize the library.

Handle large attachments and inline/embedded images with low memory use.

It is a free and open source you can Download Swift Mailer and upload to your server. (The feature list is copied from owner website).

The working example of Gmail SSL/SMTP and Swift Mailer is here...

// Swift Mailer Library
require_once '../path/to/lib/swift_required.php';

// Mail Transport
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
    ->setUsername('[email protected]') // Your Gmail Username
    ->setPassword('my_secure_gmail_password'); // Your Gmail Password

// Mailer
$mailer = Swift_Mailer::newInstance($transport);

// Create a message
$message = Swift_Message::newInstance('Wonderful Subject Here')
    ->setFrom(array('[email protected]' => 'Sender Name')) // can be $_POST['email'] etc...
    ->setTo(array('[email protected]' => 'Receiver Name')) // your email / multiple supported.
    ->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');

// Send the message
if ($mailer->send($message)) {
    echo 'Mail sent successfully.';
} else {
    echo 'I am sure, your configuration are not correct. :(';
}

I hope this helps. Happy coding... :)

OR operator in switch-case?

dude do like this

    case R.id.someValue :
    case R.id.someOtherValue :
       //do stuff

This is same as using OR operator between two values Because of this case operator isn't there in switch case

Auto highlight text in a textbox control

 textBoxX1.Focus();
 this.ActiveControl = textBoxX1;
 textBoxX1.SelectAll();

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

I got the same error with something like:

Set rs = dbs.OpenRecordset _
( _
  "SELECT Field1, Field2, FieldN " _
  & "FROM Query1 " _
  & "WHERE Query2.Field1 = """ & Value1 & """;" _
, dbOpenSnapshot _
)

I fixed the error by replacing "Query1" with "Query2"

Get filename in batch for loop

When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.

FOR /R C:\Directory %F in (*.*) do echo %~nF

should echo only the filenames.

Position an element relative to its container

I know I am late but hope this helps.

Following are the values for the position property.

  • static
  • fixed
  • relative
  • absolute

position : static

This is default. It means the element will occur at a position that it normally would.

#myelem {
    position : static;
}

position : fixed

This will set the position of an element with respect to the browser window (viewport). A fixed positioned element will remain in its position even when the page scrolls.

(Ideal if you want scroll-to-top button at the bottom right corner of the page).

#myelem {
    position : fixed;
    bottom : 30px;
    right : 30px;
}

position : relative

To place an element at a new location relative to its original position.

#myelem {
    position : relative;
    left : 30px;
    top : 30px;
}

The above CSS will move the #myelem element 30px to the left and 30px from the top of its actual location.

position : absolute

If we want an element to be placed at an exact position in the page.

#myelem {
    position : absolute;
    top : 30px;
    left : 300px;
}

The above CSS will position #myelem element at a position 30px from top and 300px from the left in the page and it will scroll with the page.

And finally...

position relative + absolute

We can set the position property of a parent element to relative and then set the position property of the child element to absolute. This way we can position the child relative to the parent at an absolute position.

#container {
    position : relative;
}

#div-2 {
    position : absolute;
    top : 0;
    right : 0;
}

Absolute position of a child element w.r.t. a Relative positioned parent element.

We can see in the above image the #div-2 element is positioned at the top-right corner inside the #container element.

GitHub: You can find the HTML of the above image here and CSS here.

Hope this tutorial helps.

get specific row from spark dataframe

This Works for me in PySpark

df.select("column").collect()[0][0]

How to get Wikipedia content using Wikipedia's API?

See Is there a clean wikipedia API just for retrieve content summary? for other proposed solutions. Here is one that I suggested:

There is actually a very nice prop called extracts that can be used with queries designed specifically for this purpose. Extracts allow you to get article extracts (truncated article text). There is a parameter called exintro that can be used to retrieve the text in the zeroth section (no additional assets like images or infoboxes). You can also retrieve extracts with finer granularity such as by a certain number of characters (exchars) or by a certain number of sentences(exsentences)

Here is a sample query http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow and the API sandbox http://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow to experiment more with this query.

Please note that if you want the first paragraph specifically you still need to get the first tag. However in this API call there are no additional assets like images to parse. If you are satisfied with this intro summary you can retrieve the text by running a function like php's strip_tag that remove the html tags.

Git clone without .git directory

You can always do

git clone git://repo.org/fossproject.git && rm -rf fossproject/.git

How to Generate a random number of fixed length using JavaScript?

More generally, generating a random integer with fixed length can be done using Math.pow:

var randomFixedInteger = function (length) {
    return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
}

To answer the question: randomFixedInteger(6);

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

MySQL DAYOFWEEK() - my week begins with monday

You can easily use the MODE argument:

MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions

If the mode argument is omitted, the value of the default_week_format system variable is used:

MySQL :: MySQL 5.1 Reference Manual :: 5.1.4 Server System Variables

Can You Get A Users Local LAN IP Address Via JavaScript?

_x000D_
_x000D_
function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs_x000D_
  //compatibility for firefox and chrome_x000D_
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;_x000D_
  var pc = new myPeerConnection({_x000D_
      iceServers: []_x000D_
    }),_x000D_
    noop = function() {},_x000D_
    localIPs = {},_x000D_
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,_x000D_
    key;_x000D_
_x000D_
  function iterateIP(ip) {_x000D_
    if (!localIPs[ip]) onNewIP(ip);_x000D_
    localIPs[ip] = true;_x000D_
  }_x000D_
  onNewIP_x000D_
  //create a bogus data channel_x000D_
  pc.createDataChannel("");_x000D_
_x000D_
  // create offer and set local description_x000D_
  pc.createOffer().then(function(sdp) {_x000D_
    sdp.sdp.split('\n').forEach(function(line) {_x000D_
      if (line.indexOf('candidate') < 0) return;_x000D_
      line.match(ipRegex).forEach(iterateIP);_x000D_
    });_x000D_
_x000D_
    pc.setLocalDescription(sdp, noop, noop);_x000D_
  }).catch(function(reason) {_x000D_
    // An error occurred, so handle the failure to connect_x000D_
  });_x000D_
_x000D_
  //listen for candidate events_x000D_
  pc.onicecandidate = function(ice) {_x000D_
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;_x000D_
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);_x000D_
  };_x000D_
}_x000D_
getUserIP(console.log)
_x000D_
_x000D_
_x000D_

Pass command parameter to method in ViewModel in WPF?

Try this:

 public class MyVmBase : INotifyPropertyChanged
{
  private ICommand _clickCommand;
   public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
        }
    }
    
       public void MyAction(object message)
    {
        if(message == null)
        {
            Notify($"Method {message} not defined");
            return;
        }
        switch (message.ToString())
        {
            case "btnAdd":
                {
                    btnAdd_Click();
                    break;
                }

            case "BtnEdit_Click":
                {
                    BtnEdit_Click();
                    break;
                }

            default:
                throw new Exception($"Method {message} not defined");
                break;
        }
    }
}

  public class CommandHandler : ICommand
{
    private Action<object> _action;
    private Func<object, bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action<object> action, Func<object, bool> canExecute)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
        _canExecute = canExecute ?? (x => true);
    }
    public CommandHandler(Action<object> action) : this(action, null)
    {
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _action(parameter);
    }
    public void Refresh()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

And in xaml:

     <Button
    Command="{Binding ClickCommand}"
    CommandParameter="BtnEdit_Click"/>

Java: Insert multiple rows into MySQL with PreparedStatement

@Ali Shakiba your code needs some modification. Error part:

for (int i = 0; i < myArray.length; i++) {
     myStatement.setString(i, myArray[i][1]);
     myStatement.setString(i, myArray[i][2]);
}

Updated code:

String myArray[][] = {
    {"1-1", "1-2"},
    {"2-1", "2-2"},
    {"3-1", "3-2"}
};

StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");

for (int i = 0; i < myArray.length - 1; i++) {
    mySql.append(", (?, ?)");
}

mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());

for (int i = 0; i < myArray.length; i++) {
    myStatement.setString((2 * i) + 1, myArray[i][1]);
    myStatement.setString((2 * i) + 2, myArray[i][2]);
}

myStatement.executeUpdate();

best way to get the key of a key/value javascript object

Object.keys() The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr1 = Object.keys(obj);

Object.values() The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var arr2 = Object.values(obj);

For more please go here

How can I transform string to UTF-8 in C#?

 Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(mystring));

How can I get the current network interface throughput statistics on Linux/UNIX?

  • dstat - Combines vmstat, iostat, ifstat, netstat information and more
  • iftop - Amazing network bandwidth utility to analyse what is really happening on your eth
  • netio - Measures the net throughput of a network via TCP/IP
  • inq - CLI troubleshooting utility that displays info on storage, typically Symmetrix. By default, INQ returns the device name, Symmetrix ID, Symmetrix LUN, and capacity.
  • send_arp - Sends out an arp broadcast on the specified network device (defaults to eth0), reporting an old and new IP address mapping to a MAC address.
  • EtherApe - is a graphical network monitor for Unix modeled after etherman. Featuring link layer, IP and TCP modes, it displays network activity graphically.
  • iptraf - An IP traffic monitor that shows information on the IP traffic passing over your network.

More details: http://felipeferreira.net/?p=1194

How to import an Oracle database from dmp file and log file?

How was the database exported?

  • If it was exported using exp and a full schema was exported, then

    1. Create the user:

      create user <username> identified by <password> default tablespace <tablespacename> quota unlimited on <tablespacename>;
      
    2. Grant the rights:

      grant connect, create session, imp_full_database to <username>;
      
    3. Start the import with imp:

      imp <username>/<password>@<hostname> file=<filename>.dmp log=<filename>.log full=y;
      
  • If it was exported using expdp, then start the import with impdp:

    impdp <username>/<password> directory=<directoryname> dumpfile=<filename>.dmp logfile=<filename>.log full=y;
    

Looking at the error log, it seems you have not specified the directory, so Oracle tries to find the dmp file in the default directory (i.e., E:\app\Vensi\admin\oratest\dpdump\).

Either move the export file to the above path or create a directory object to pointing to the path where the dmp file is present and pass the object name to the impdp command above.

Google Colab: how to read data from my google drive?

You can't permanently store a file on colab. Though you can import files from your drive and everytime when you are done with file you can save it back.

To mount the google drive to your Colab session

from google.colab import drive
drive.mount('/content/gdrive')

you can simply write to google drive as you would to a local file system Now if you see your google drive will be loaded in the Files tab. Now you can access any file from your colab, you can write as well as read from it. The changes will be done real time on your drive and anyone having the access link to your file can view the changes made by you from your colab.

Example

with open('/content/gdrive/My Drive/filename.txt', 'w') as f:
   f.write('values')

Is it possible to make Font Awesome icons larger than 'fa-5x'?

  1. Just add the font awesome class like this:

    class="fa fa-plus-circle fa-3x"
    

    (You can increase the size as per 5x, 7x, 9x..)

  2. You can also add custom CSS.

Compare two MySQL databases

I think Navicat for MySQL will be helpful for this case. It supports Data and Structure Synchronization for MySQL. enter image description here

0xC0000005: Access violation reading location 0x00000000

"Access violation reading location 0x00000000" means that you're derefrencing a pointer that hasn't been initialized and therefore has garbage values. Those garbage values could be anything, but usually it happens to be 0 and so you try to read from the memory address 0x0, which the operating system detects and prevents you from doing.

Check and make sure that the array invaders[] is what you think it should be.

Also, you don't seem to be updating i ever - meaning that you keep placing the same Invader object into location 0 of invaders[] at every loop iteration.

Converting byte array to String (Java)

You can try this.

String s = new String(bytearray);

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

Assign a variable inside a Block to a variable outside a Block

When I saw the same error, I tried to resolve it like:

   __block CGFloat docHeight = 0.0;


    [self evaluateJavaScript:@"document.height" completionHandler:^(id height, NSError *error) {
        //height
        NSLog(@"=========>document.height:@%@",height);
        docHeight = [height floatValue];
    }];

and its working fine

Just add "__block" before Variable.

How to remove all MySQL tables from the command-line without DROP database permissions?

You can drop the database and then recreate it with the below:-

mysql> drop database [database name];
mysql> create database [database name];

Why can't C# interfaces contain fields?

Beginning with C# 8.0, an interface may define a default implementation for members, including properties. Defining a default implementation for a property in an interface is rare because interfaces may not define instance data fields.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties

interface IEmployee
{
    string Name
    {
        get;
        set;
    }

    int Counter
    {
        get;
    }
}

public class Employee : IEmployee
{
    public static int numberOfEmployees;

    private string _name;
    public string Name  // read-write instance property
    {
        get => _name;
        set => _name = value;
    }

    private int _counter;
    public int Counter  // read-only instance property
    {
        get => _counter;
    }

    // constructor
    public Employee() => _counter = ++numberOfEmployees;
}

How do I convert a string to a number in PHP?

PHP will do it for you within limits

<?php
   $str = "3.148";
   $num = $str;

   printf("%f\n", $num);
?>

Making the iPhone vibrate

Swift 2.0+

AudioToolbox now presents the kSystemSoundID_Vibrate as a SystemSoundID type, so the code is:

import AudioToolbox.AudioServices

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)

Instead of having to go thru the extra cast step

(Props to @Dov)

Original Answer (Swift 1.x)

And, here's how you do it on Swift (in case you ran into the same trouble as I did)

Link against AudioToolbox.framework (Go to your project, select your target, build phases, Link Binary with Libraries, add the library there)

Once that is completed:

import AudioToolbox.AudioServices

// Use either of these
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

The cheesy thing is that SystemSoundID is basically a typealias (fancy swift typedef) for a UInt32, and the kSystemSoundID_Vibrate is a regular Int. The compiler gives you an error for trying to cast from Int to UInt32, but the error reads as "Cannot convert to SystemSoundID", which is confusing. Why didn't apple just make it a Swift enum is beyond me.

@aponomarenko's goes into the details, my answer is just for the Swifters out there.

General error: 1364 Field 'user_id' doesn't have a default value

 Post::create([
      'title' => request('title'),
      'body' => request('body'),
      'user_id' => auth()->id()
    ]);

you dont need the request() as you doing that already pulling the value of body and title

Undo git update-index --assume-unchanged <file>

I assume (heh) you meant --assume-unchanged, since I don't see any --assume-changed option. The inverse of --assume-unchanged is --no-assume-unchanged.

jquery dialog save cancel button styling

These solutions are all very well if you only have one dialog in the page at any one time, however if you want to style multiple dialogs at once then try:

$("#element").dialog({
    buttons: {
        'Save': function() {},
        'Cancel': function() {}
    }
})
.dialog("widget")
.find(".ui-dialog-buttonpane button")
.eq(0).addClass("btnSave").end()
.eq(1).addClass("btnCancel").end();

Instead of globally selecting buttons, this gets the widget object and finds it's button pane, then individually styles each button. This saves lot's of pain when you have several dialogs on one page

force css grid container to fill full screen of device

You can add position: fixed; with top left right bottom 0 attribute, that solution work on older browsers too.

If you want to embed it, add position: absolute; to the wrapper, and position: relative to the div outside of the wrapper.

_x000D_
_x000D_
.wrapper {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
_x000D_
  display: grid;_x000D_
  border-style: solid;_x000D_
  border-color: red;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-template-rows: repeat(3, 1fr);_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
  border-style: solid;_x000D_
  border-color: blue;_x000D_
  grid-column: 1 / 3;_x000D_
  grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
  border-style: solid;_x000D_
  border-color: yellow;_x000D_
  grid-column: 2 / 4;_x000D_
  grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
  border-style: solid;_x000D_
  border-color: violet;_x000D_
  grid-row: 2 / 5;_x000D_
  grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
  border-style: solid;_x000D_
  border-color: aqua;_x000D_
  grid-column: 3;_x000D_
  grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
  border-style: solid;_x000D_
  border-color: green;_x000D_
  grid-column: 2;_x000D_
  grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
  border-style: solid;_x000D_
  border-color: purple;_x000D_
  grid-column: 3;_x000D_
  grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
  <div class="one">One</div>_x000D_
  <div class="two">Two</div>_x000D_
  <div class="three">Three</div>_x000D_
  <div class="four">Four</div>_x000D_
  <div class="five">Five</div>_x000D_
  <div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

C# Lambda expressions: Why should I use them?

Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.

Consider this example:

 List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };
 string person = people.Find(person => person.Contains("Joe"));

versus

 public string FindPerson(string nameContains, List<string> persons)
 {
     foreach (string person in persons)
         if (person.Contains(nameContains))
             return person;
     return null;
 }

These are functionally equivalent.

Disabling browser caching for all browsers from ASP.NET

This is what we use in ASP.NET:

// Stop Caching in IE
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);

// Stop Caching in Firefox
Response.Cache.SetNoStore();

It stops caching in Firefox and IE, but we haven't tried other browsers. The following response headers are added by these statements:

Cache-Control: no-cache, no-store
Pragma: no-cache

Bash script processing limited number of commands in parallel

See parallel. Its syntax is similar to xargs, but it runs the commands in parallel.

Max tcp/ip connections on Windows Server 2008

There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:

It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

How to rename files and folder in Amazon S3?

We have 2 ways by which we can rename a file on AWS S3 storage -

1 .Using the CLI tool -

aws s3 --recursive mv s3://bucket-name/dirname/oldfile s3://bucket-name/dirname/newfile

2.Using SDK

$s3->copyObject(array(
'Bucket'     => $targetBucket,
'Key'        => $targetKeyname,
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",));

When does a process get SIGABRT (signal 6)?

abort() sends the calling process the SIGABRT signal, this is how abort() basically works.

abort() is usually called by library functions which detect an internal error or some seriously broken constraint. For example malloc() will call abort() if its internal structures are damaged by a heap overflow.

Setting mime type for excel document

Waking up an old thread here I see, but I felt the urge to add the "new" .xlsx format.

According to http://filext.com/file-extension/XLSX the extension for .xlsx is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. It might be a good idea to include it when checking for mime types!

Set a button background image iPhone programmatically

Complete code:

+ (UIButton *)buttonWithTitle:(NSString *)title
                       target:(id)target
                     selector:(SEL)selector
                        frame:(CGRect)frame
                        image:(UIImage *)image
                 imagePressed:(UIImage *)imagePressed
                darkTextColor:(BOOL)darkTextColor
{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];

    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];


    UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newImage forState:UIControlStateNormal];

    UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];

    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];

    // in case the parent view draws with a custom color or gradient, use a transparent color
    button.backgroundColor = [UIColor clearColor];

    return button;
}

UIImage *buttonBackground = UIImage imageNamed:@"whiteButton.png";
UIImage *buttonBackgroundPressed = UIImage imageNamed:@"blueButton.png";

CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight);

UIButton *button = [FinishedStatsView buttonWithTitle:title
                                               target:target
                                             selector:action
                                                frame:frame
                                                image:buttonBackground
                                         imagePressed:buttonBackgroundPressed
                                        darkTextColor:YES];

[self addSubview:button]; 

To set an image:

UIImage *buttonImage = [UIImage imageNamed:@"Home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

To remove an image:

[button setBackgroundImage:nil forState:UIControlStateNormal];

UILabel with text of two different colors

My answer has also the option to color all the occurrence of a text not only one occurrence of it : "wa ba wa ba dubdub" , you can color all the occurrence of wa not only the first occurrence like the accepted answer.

extension NSMutableAttributedString{
    func setColorForText(_ textToFind: String, with color: UIColor) {
        let range = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        if range.location != NSNotFound {
            addAttribute(NSForegroundColorAttributeName, value: color, range: range)
        }
    }

    func setColorForAllOccuranceOfText(_ textToFind: String, with color: UIColor) {
        let inputLength = self.string.count
        let searchLength = textToFind.count
        var range = NSRange(location: 0, length: self.length)

        while (range.location != NSNotFound) {
            range = (self.string as NSString).range(of: textToFind, options: [], range: range)
            if (range.location != NSNotFound) {
                self.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: range.location, length: searchLength))
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
            }
        }
    }
}

Now you can do this :

let message = NSMutableAttributedString(string: "wa ba wa ba dubdub")
message.setColorForText(subtitle, with: UIColor.red) 
// or the below one if you want all the occurrence to be colored 
message.setColorForAllOccuranceOfText("wa", with: UIColor.red) 
// then you set this attributed string to your label :
lblMessage.attributedText = message

Display only 10 characters of a long string?

('very long string'.slice(0,10))+'...'
// "very long ..."

URLEncoder not able to translate space character

Check out the java.net.URI class.

kill a process in bash

Please check "top" command then if your script or any are running please note 'PID'

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 1384 root      20   0  514m  32m 2188 S  0.3  5.4  55:09.88 example
14490 root      20   0 15140 1216  920 R  0.3  0.2   0:00.02 example2



kill <you process ID>

Example : kill 1384

Sort ArrayList of custom Objects by property

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

Start HTML5 video at a particular position when loading?

adjust video start and end time when using the video tag in html5;

http://www.yoursite.com/yourfolder/yourfile.mp4#t=5,15

where left of comma is start time in seconds, right of comma is end time in seconds. drop the comma and end time to effect the start time only.

How to convert current date to epoch timestamp?

if you want UTC try some of the gm functions:

import time
import calendar

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
print utc_epoch

Invoking Java main method with parameters from Eclipse

AFAIK there isn't a built-in mechanism in Eclipse for this.

The closest you can get is to create a wrapper that prompts you for these values and invokes the (hardcoded) main. You then get you execution history as long as you don't clear terminated processes. Two variations on this are either to use JUNit, or to use injection or parameter so that your wrapper always connects to the correct class for its main.

Get UserDetails object from Security Context in Spring MVC controller

If you already know for sure that the user is logged in (in your example if /index.html is protected):

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
        // userDetails = auth.getPrincipal()
}

How to export private key from a keystore of self-signed certificate

It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12. [note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]

keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:  
Re-enter new password: 
Enter source keystore password:  
[Storing myp12file.p12]

Now the file myp12file.p12 contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12 command. For example,

openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
    friendlyName: mykey
    localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37 
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----

Prints out the private key unencrypted.

Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How do I determine if a port is open on a Windows server?

Another utility that I found and is good and small as well, is PortQry Command Line Port Scanner version 2.0.

You can ping a server and a port and it will tell you the state of the port. There is a command-line utility and a UI for it.

How to add a list item to an existing unordered list?

This is another one

$("#header ul li").last().html('<li> Menu 5 </li>');

Calculating the position of points in a circle

Placing a number in a circular path

// variable

let number = 12; // how many number to be placed
let size = 260; // size of circle i.e. w = h = 260
let cx= size/2; // center of x(in a circle)
let cy = size/2; // center of y(in a circle)
let r = size/2; // radius of a circle

for(let i=1; i<=number; i++) {
  let ang = i*(Math.PI/(number/2));
  let left = cx + (r*Math.cos(ang));
  let top = cy + (r*Math.sin(ang));
  console.log("top: ", top, ", left: ", left);
}

Build error: "The process cannot access the file because it is being used by another process"

One more solution: when the files get locked, blocking process is reported (something like "ServiceHub.Host.CLR.x64 (7764)") with it's id in parentheses. To get rid of the process, open PowerShell (x + Win + I) and type: "Stop-Process -Id idNumber".

Empty ArrayList equals null

If you want to check whether the array contains items with null values, use this:

private boolean isListOfNulls(ArrayList<String> stringList){
    for (String s: stringList)
        if( s != null) return false;
    return true;
}

You could replace <String> with the corresponding type for your ArrayList

Adding background image to div using CSS

It is happening because .header-shadow is empty.

Add height to it:

.header-shadow{
    background-image: url('../images/header-shade.jpg');
    background-color: red;
    height: 50px;
}

Fiddle here.

AngularJS ng-click to go to another page (with Ionic framework)

app.controller('NavCtrl', function ($scope, $location, $state, $window, Post, Auth) {
    $scope.post = {url: 'http://', title: ''};

    $scope.createVariable = function(url) {
      $window.location.href = url;
    };
    $scope.createFixed = function() {
      $window.location.href = '/tab/newpost';
    };
});

HTML

<button class="button button-icon ion-compose" ng-click="createFixed()"></button>
<button class="button button-icon ion-compose" ng-click="createVariable('/tab/newpost')"></button>

Prompt Dialog in Windows Forms

Unfortunately C# still doesn't offer this capability in the built in libs. The best solution at present is to create a custom class with a method that pops up a small form. If you're working in Visual Studio you can do this by clicking on Project >Add class

Add Class

Visual C# items >code >class Add Class 2

Name the class PopUpBox (you can rename it later if you like) and paste in the following code:

using System.Drawing;
using System.Windows.Forms;

namespace yourNameSpaceHere
{
    public class PopUpBox
    {
        private static Form prompt { get; set; }

        public static string GetUserInput(string instructions, string caption)
        {
            string sUserInput = "";
            prompt = new Form() //create a new form at run time
            {
                Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption,
                StartPosition = FormStartPosition.CenterScreen, TopMost = true
            };
            //create a label for the form which will have instructions for user input
            Label lblTitle = new Label() { Left = 50, Top = 20, Text = instructions, Dock = DockStyle.Top, TextAlign = ContentAlignment.TopCenter };
            TextBox txtTextInput = new TextBox() { Left = 50, Top = 50, Width = 400 };

            ////////////////////////////OK button
            Button btnOK = new Button() { Text = "OK", Left = 250, Width = 100, Top = 70, DialogResult = DialogResult.OK };
            btnOK.Click += (sender, e) => 
            {
                sUserInput = txtTextInput.Text;
                prompt.Close();
            };
            prompt.Controls.Add(txtTextInput);
            prompt.Controls.Add(btnOK);
            prompt.Controls.Add(lblTitle);
            prompt.AcceptButton = btnOK;
            ///////////////////////////////////////

            //////////////////////////Cancel button
            Button btnCancel = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.Cancel };
            btnCancel.Click += (sender, e) => 
            {
                sUserInput = "cancel";
                prompt.Close();
            };
            prompt.Controls.Add(btnCancel);
            prompt.CancelButton = btnCancel;
            ///////////////////////////////////////

            prompt.ShowDialog();
            return sUserInput;
        }

        public void Dispose()
        {prompt.Dispose();}
    }
}

You will need to change the namespace to whatever you're using. The method returns a string, so here's an example of how to implement it in your calling method:

bool boolTryAgain = false;

do
{
    string sTextFromUser = PopUpBox.GetUserInput("Enter your text below:", "Dialog box title");
    if (sTextFromUser == "")
    {
        DialogResult dialogResult = MessageBox.Show("You did not enter anything. Try again?", "Error", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            boolTryAgain = true; //will reopen the dialog for user to input text again
        }
        else if (dialogResult == DialogResult.No)
        {
            //exit/cancel
            MessageBox.Show("operation cancelled");
            boolTryAgain = false;
        }//end if
    }
    else
    {
        if (sTextFromUser == "cancel")
        {
            MessageBox.Show("operation cancelled");
        }
        else
        {
            MessageBox.Show("Here is the text you entered: '" + sTextFromUser + "'");
            //do something here with the user input
        }

    }
} while (boolTryAgain == true);

This method checks the returned string for a text value, empty string, or "cancel" (the getUserInput method returns "cancel" if the cancel button is clicked) and acts accordingly. If the user didn't enter anything and clicked OK it will tell the user and ask them if they want to cancel or re-enter their text.

Post notes: In my own implementation I found that all of the other answers were missing 1 or more of the following:

  • A cancel button
  • The ability to contain symbols in the string sent to the method
  • How to access the method and handle the returned value.

Thus, I have posted my own solution. I hope someone finds it useful. Credit to Bas and Gideon + commenters for your contributions, you helped me to come up with a workable solution!

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

while EOF in JAVA?

The others told you enough about your issue with multiple calls of readLine().

I just wanted to leave sth about code style: While you see this line = assignement and != null check together in one while condition in most examples (like @gotomanners example here) I prefer using a for for it.

It is much more readable in my opinion ...

for (String line = in.readLine(); line != null; line = in.readLine()) {
    ...
}

Another nice way to write it you see in @TheCapn's example. But when you write it that way you easily see that's what a for-loop is made for.

I do not like assignments scrambled with conditions in one line. It is bad style in my opinion. But because it is so MUCH popular for that special case here to do it that way I would not consider it really bad style. (But cannot understand who established this bad style to become that popular.)

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

try to add ojdbc6.jar through the server lib "C:\apache-tomcat-7.0.47\lib",

Then restart the server in eclipse.

How to Parse JSON Array with Gson

Some of the answers of this post are valid, but using TypeToken, the Gson library generates a Tree objects whit unreal types for your application.

To get it I had to read the array and convert one by one the objects inside the array. Of course this method is not the fastest and I don't recommend to use it if you have the array is too big, but it worked for me.

It is necessary to include the Json library in the project. If you are developing on Android, it is included:

/**
 * Convert JSON string to a list of objects
 * @param sJson String sJson to be converted
 * @param tClass Class
 * @return List<T> list of objects generated or null if there was an error
 */
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){

    try{
        Gson gson = new Gson();
        List<T> listObjects = new ArrayList<>();

        //read each object of array with Json library
        JSONArray jsonArray = new JSONArray(sJson);
        for(int i=0; i<jsonArray.length(); i++){

            //get the object
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            //get string of object from Json library to convert it to real object with Gson library
            listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
        }

        //return list with all generated objects
        return listObjects;

    }catch(Exception e){
        e.printStackTrace();
    }

    //error: return null
    return null;
}

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

Null must not be set to string...

$this->db->where('archived IS NOT', null);

It works properly when null is not wrapped into quotes.

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

Git commit date

If you like to have the timestamp without the timezone but local timezone do

git log -1 --format=%cd --date=local

Which gives this depending on your location

Mon Sep 28 12:07:37 2015

Mockito. Verify method arguments

  • You don't need the eq matcher if you don't use other matchers.
  • You are not using the correct syntax - your method call should be outside the .verify(mock). You are now initiating verification on the result of the method call, without verifying anything (not making a method call). Hence all tests are passing.

You code should look like:

Mockito.verify(mock).mymethod(obj);
Mockito.verify(mock).mymethod(null);
Mockito.verify(mock).mymethod("something_else");

How to debug an apache virtual host configuration?

Syntax check

To check configuration files for syntax errors:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -t

# Debian-based (Ubuntu)
apache2ctl -t

# MacOS
apachectl -t

List virtual hosts

To list all virtual hosts, and their locations:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -S

# Debian-based (Ubuntu)
apache2ctl -S

# MacOS
apachectl -S

Disabling user input for UITextfield in swift

Swift 4.2 / Xcode 10.1:

Just uncheck behavior Enabled in your storyboard -> attributes inspector.

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

no match for ‘operator<<’ in ‘std::operator

Object is a collection of methods and variables.You can't print the variables in object by just cout operation . if you want to show the things inside the object you have to declare either a getter or a display text method in class.

ex

#include <iostream>

using namespace std;

class mystruct

{
private:
    int m_a;
    float m_b;

public:
    mystruct(int x, float y)
    {
            m_a = x;
            m_b = y;
    }
    public:
    void getm_aAndm_b()
    {
        cout<<m_a<<endl;
        cout<<m_b<<endl;
    }



};

int main()
{

    mystruct m = mystruct(5,3.14);

    cout << "my structure " << endl;
    m.getm_aAndm_b();
    return 0;

}

Not that this is just a one way of doing it

Restart container within pod

All the above answers have mentioned deleting the pod...but if you have many pods of the same service then it would be tedious to delete each one of them...

Therefore, I propose the following solution, restart:

  • 1) Set scale to zero :

     kubectl scale deployment <<name>> --replicas=0 -n service 
    

    The above command will terminate all your pods with the name <<name>>

  • 2) To start the pod again, set the replicas to more than 0

    kubectl scale deployment <<name>> --replicas=2 -n service
    

    The above command will start your pods again with 2 replicas.

How to check whether java is installed on the computer

Type in the command window

java -version

If it gives an output everything should be fine. If you want to develop software you might want to set the PATH.

Local variable referenced before assignment?

Best solution: Don't use globals

>>> test1 = 0
>>> def test_func(x):
        return x + 1

>>> test1 = test_func(test1)
>>> test1
1

Can someone give an example of cosine similarity, in a very simple, graphical way?

This is a simple Python code which implements cosine similarity.

from scipy import linalg, mat, dot
import numpy as np

In [12]: matrix = mat( [[2, 1, 0, 2, 0, 1, 1, 1],[2, 1, 1, 1, 1, 0, 1, 1]] )

In [13]: matrix
Out[13]: 
matrix([[2, 1, 0, 2, 0, 1, 1, 1],
        [2, 1, 1, 1, 1, 0, 1, 1]])
In [14]: dot(matrix[0],matrix[1].T)/np.linalg.norm(matrix[0])/np.linalg.norm(matrix[1])
Out[14]: matrix([[ 0.82158384]])

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais

How to add a WiX custom action that happens only on uninstall (via MSI)?

There are multiple problems with yaluna's answer, also property names are case sensitive, Installed is the correct spelling (INSTALLED will not work). The table above should've been this:

enter image description here

Also assuming a full repair & uninstall the actual values of properties could be:

enter image description here

The WiX Expression Syntax documentation says:

In these expressions, you can use property names (remember that they are case sensitive).

The properties are documented at the Windows Installer Guide (e.g. Installed)

EDIT: Small correction to the first table; evidently "Uninstall" can also happen with just REMOVE being True.

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

Display text from .txt file in batch file

hmm.. just found the answer. it's easier then i thought. it just needs a bunch more stuff:

@echo off
if not exist log.txt GOTO :write
echo Date/Time last login:
type log.txt
del log.txt
:write
echo %date%, %time%. >> log.txt
@pause
exit

So it first reads the log.txt file and deletes it. After that it just get a new file (log.txt) with the date & time!

I hope this helps other people!

(the only prob is that the first time it does not work, but then just enter in random value at log.txt.) (This problem is solved and edited.)

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

Sol 1: In build.gradle:

defaultConfig {
    multiDexEnabled true
}

Clean your project and rebuild.

Sol 2: in local.properties add,

org.gradle.jvmargs=-XX\:MaxHeapSize\=512m -Xmx512m

Sol 3

compile 'com.android.support:multidex:1.0.1'

Else add all 3 in your application.

How to use router.navigateByUrl and router.navigate in Angular

From my understanding, router.navigate is used to navigate relatively to current path. For eg : If our current path is abc.com/user, we want to navigate to the url : abc.com/user/10 for this scenario we can use router.navigate .


router.navigateByUrl() is used for absolute path navigation.

ie,

If we need to navigate to entirely different route in that case we can use router.navigateByUrl

For example if we need to navigate from abc.com/user to abc.com/assets, in this case we can use router.navigateByUrl()


Syntax :

router.navigateByUrl(' ---- String ----');

router.navigate([], {relativeTo: route})

Print: Entry, ":CFBundleIdentifier", Does Not Exist

For [email protected] the following did the trick for me:

1) Check your paths, open your .xcodeproj (not .xcworkspace) file and:

  • go to File > Project Settings > Advanced

  • custom > Relative to workspace

  • set the products path to 'build/Build/Products'
  • set the intermediates path to 'build/Build/Intermediates'
  • press done and save your changes

2) Run rm -rf ios/build in your project's root directory

3) Close your react packager

4) Run react-native run-ios again

How do you properly use WideCharToMultiByte

Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <string.h>

/* string consisting of several Asian characters */
wchar_t wcsString[] = L"\u9580\u961c\u9640\u963f\u963b\u9644";

int main() 
{

    size_t wcsChars = wcslen( wcsString);

    size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, 
                                               NULL, 0,  NULL, NULL);

    printf( "Wide chars in wcsString: %u\n", wcsChars);
    printf( "Bytes required for CP950 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);

    sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,
                                        NULL, 0,  NULL, NULL);
    printf( "Bytes required for UTF8 encoding (excluding NUL terminator): %u\n",
             sizeRequired-1);
}

And the output:

Wide chars in wcsString: 6
Bytes required for CP950 encoding (excluding NUL terminator): 12
Bytes required for UTF8 encoding (excluding NUL terminator): 18

How to get a view table query (code) in SQL Server 2008 Management Studio

if i understood you can do the following

Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window

Pass Parameter to Gulp Task

If you want to use environment params and other utils as well such as log, you can use gulp-util

/* 
  $npm install gulp-util --save-dev
  $gulp --varName 123
*/
var util = require('gulp-util');
util.log(util.env.varName);

Update

gulp-util is now deprecated. You can use minimist instead.

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);

Http 415 Unsupported Media type error with JSON

The reason can be not adding "annotation-driven" in your dispatcher servlet xml file. and also it may be due to not adding as application/json in the headers

Parsing huge logfiles in Node.js - read in line-by-line

You can use the inbuilt readline package, see docs here. I use stream to create a new output stream.

var fs = require('fs'),
    readline = require('readline'),
    stream = require('stream');

var instream = fs.createReadStream('/path/to/file');
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;

var rl = readline.createInterface({
    input: instream,
    output: outstream,
    terminal: false
});

rl.on('line', function(line) {
    console.log(line);
    //Do your stuff ...
    //Then write to outstream
    rl.write(cubestuff);
});

Large files will take some time to process. Do tell if it works.

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

Laravel 5 - How to access image uploaded in storage within View?

According to Laravel 5.2 docs, your publicly accessible files should be put in directory

storage/app/public

To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public.

ln -s /path/to/laravel/storage/app/public /path/to/laravel/public/storage

Now you can create in your view an URL to the files using the asset helper:

echo asset('storage/file.txt');